디시인사이드 갤러리

갤러리 이슈박스, 최근방문 갤러리

갤러리 본문 영역

지피티 5로 코드 뱉어봤는데 여전히 좀 아쉽

ㅆㅇㅆ(124.216) 2025.08.08 10:17:06
조회 79 추천 0 댓글 0

using System;

using System.Buffers;

using System.Collections.Concurrent;

using System.Collections.Generic;

using System.Linq;

using System.Threading;

using System.Threading.Tasks;


/// <summary>

/// 데이터 처리 파이프라인 예제

/// - OOP: 클래스/인터페이스로 모듈화

/// - FP: 불변 데이터, 순수 함수 처리

/// - DOP: 캐시 친화적 배열 처리

/// - Thread-safe 이벤트 시스템

/// </summary>

namespace HighPerformancePipeline

{

    #region Interfaces

    public interface IDataProcessor<TInput, TOutput>

    {

        Task ProcessAsync(IEnumerable<TInput> inputData, CancellationToken token = default);

        event Action<IReadOnlyList<TOutput>> OnProcessingCompleted;

    }

    #endregion


    #region Immutable Data

    /// <summary>

    /// 불변 데이터 레코드 (FP 스타일)

    /// </summary>

    public readonly record struct ProcessedResult(int Id, double Value);

    #endregion


    #region Implementation

    public class ParallelDataProcessor : IDataProcessor<int, ProcessedResult>

    {

        public event Action<IReadOnlyList<ProcessedResult>> OnProcessingCompleted;


        private readonly int batchSize;

        private readonly Func<int, double> transformation;


        public ParallelDataProcessor(int batchSize, Func<int, double> transformation)

        {

            if (batchSize <= 0) throw new ArgumentOutOfRangeException(nameof(batchSize));

            this.batchSize = batchSize;

            this.transformation = transformation ?? throw new ArgumentNullException(nameof(transformation));

        }


        public async Task ProcessAsync(IEnumerable<int> inputData, CancellationToken token = default)

        {

            if (inputData == null) throw new ArgumentNullException(nameof(inputData));


            // Thread-safe 컬렉션

            ConcurrentBag<ProcessedResult> results = new ConcurrentBag<ProcessedResult>();


            // 데이터 분할 (DOP - 캐시 친화적 배치)

            int[][] batches = inputData

                .Select((value, index) => new { value, index })

                .GroupBy(x => x.index / batchSize)

                .Select(g => g.Select(x => x.value).ToArray())

                .ToArray();


            await Task.Run(() =>

            {

                Parallel.ForEach(batches, new ParallelOptions { CancellationToken = token }, batch =>

                {

                    // ArrayPool 사용 (GC 압박 감소)

                    double[] tempBuffer = ArrayPool<double>.Shared.Rent(batch.Length);


                    try

                    {

                        for (int i = 0; i < batch.Length; i++)

                        {

                            tempBuffer[i] = transformation(batch[i]); // 순수 함수 처리

                        }


                        for (int i = 0; i < batch.Length; i++)

                        {

                            results.Add(new ProcessedResult(batch[i], tempBuffer[i]));

                        }

                    }

                    finally

                    {

                        ArrayPool<double>.Shared.Return(tempBuffer);

                    }

                });

            }, token);


            OnProcessingCompleted?.Invoke(results.OrderBy(r => r.Id).ToList());

        }

    }

    #endregion


    #region Example Usage

    public static class Program

    {

        public static async Task Main()

        {

            // 변환 로직: sqrt 연산 + 부동소수점 연산 예시

            ParallelDataProcessor processor = new ParallelDataProcessor(

                batchSize: 1024,

                transformation: value => Math.Sqrt(value) * 1.2345

            );


            processor.OnProcessingCompleted += results =>

            {

                Console.WriteLine($"[Completed] {results.Count} items processed.");

                Console.WriteLine($"First 5 results: {string.Join(", ", results.Take(5))}");

            };


            int[] sampleData = Enumerable.Range(1, 100_000).ToArray();

            await processor.ProcessAsync(sampleData);

        }

    }

    #endregion

}



테스트 밴치 이렇게 뱉어냈는데

내가 품을 들여서

using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace HighPerformancePipeline
{
    /// <summary>
    /// 제네릭 데이터 처리기
    /// </summary>
    public interface IDataProcessor<TInput, TOutput>
    {
        Task ProcessAsync(IEnumerable<TInput> inputData, CancellationToken token = default);
        event Action<IReadOnlyList<TOutput>> OnProcessingCompleted;
    }

    /// <summary>
    /// 고성능 제네릭 병렬 처리기
    /// </summary>
    public class ParallelDataProcessor<TInput, TOutput> : IDataProcessor<TInput, TOutput>
    {
        public event Action<IReadOnlyList<TOutput>> OnProcessingCompleted;

        private readonly int batchSize;
        private readonly Func<TInput, TOutput> transformation;

        public ParallelDataProcessor(int batchSize, Func<TInput, TOutput> transformation)
        {
            if (batchSize <= 0) throw new ArgumentOutOfRangeException(nameof(batchSize));
            this.batchSize = batchSize;
            this.transformation = transformation ?? throw new ArgumentNullException(nameof(transformation));
        }

        public async Task ProcessAsync(IEnumerable<TInput> inputData, CancellationToken token = default)
        {
            if (inputData == null) throw new ArgumentNullException(nameof(inputData));

            ConcurrentBag<TOutput> results = new ConcurrentBag<TOutput>();

            // 배치 분할 (DOP)
            TInput[][] batches = inputData
                .Select((value, index) => new { value, index })
                .GroupBy(x => x.index / batchSize)
                .Select(g => g.Select(x => x.value).ToArray())
                .ToArray();

            await Task.Run(() =>
            {
                Parallel.ForEach(batches, new ParallelOptions { CancellationToken = token }, batch =>
                {
                    // ArrayPool은 value type일 때만 유의미
                    TOutput[] tempBuffer = ArrayPool<TOutput>.Shared.Rent(batch.Length);

                    try
                    {
                        for (int i = 0; i < batch.Length; i++)
                        {
                            tempBuffer[i] = transformation(batch[i]);
                        }

                        for (int i = 0; i < batch.Length; i++)
                        {
                            results.Add(tempBuffer[i]);
                        }
                    }
                    finally
                    {
                        ArrayPool<TOutput>.Shared.Return(tempBuffer);
                    }
                });
            }, token);

            OnProcessingCompleted?.Invoke(results.ToList());
        }
    }

    /// <summary>
    /// 사용 예시
    /// </summary>
    public static class Program
    {
        public static async Task Main()
        {
            // 예: int -> string 변환
            var stringProcessor = new ParallelDataProcessor<int, string>(
                batchSize: 512,
                transformation: num => $"Value={num}, Sqrt={Math.Sqrt(num):F3}"
            );

            stringProcessor.OnProcessingCompleted += results =>
            {
                Console.WriteLine($"[Completed] {results.Count} strings generated.");
                Console.WriteLine($"First 3: {string.Join(", ", results.Take(3))}");
            };

            await stringProcessor.ProcessAsync(Enumerable.Range(1, 5000));
        }
    }
}


이렇게 제네릭 타입으로 했는데

파이프 라인을 좀 더 범용화했을텐데

애초에 입출력 타입이 완전 제네릭화가 아니면 매핑 로직이 까다로운데 생각보다 별로인듯

이벤트 기반 처리도 그렇고

그리고 

이벤트 호출 쓰레드가 UI 쓰레드 일 경우 던져야할 디스패칭 로직이 빠져있음.

생각보다 여전히 문맥 문제가 심각한듯.


추천 비추천

0

고정닉 0

0

댓글 영역

전체 댓글 0
본문 보기

하단 갤러리 리스트 영역

왼쪽 컨텐츠 영역

갤러리 리스트 영역

갤러리 리스트
번호 제목 글쓴이 작성일 조회 추천
설문 현대물보다 사극에서 더 빛나는 남자 배우는? 운영자 25/09/08 - -
AD 신학기 레벨업~!! 운영자 25/09/05 - -
2886910 Ada 책 집필 방향을 변경해야겠다 나르시갤로그로 이동합니다. 09.05 45 0
2886909 너무 바빠서 러스트 깔 시간이 없다 나르시갤로그로 이동합니다. 09.05 50 0
2886908 등처먹기 하나 만큼은 특기입니다만... 프갤러(118.235) 09.05 42 0
2886907 주술회전 후속작 1화 [2] ♥냥덩이♥갤로그로 이동합니다. 09.05 80 0
2886906 뉴프로에서 기프티콘 뿌린다 [1] 개멍청한유라갤로그로 이동합니다. 09.05 60 0
2886905 오늘 저녁 내 치킨을 뜯겠습니다 [3] 루도그담당(118.235) 09.05 62 0
2886904 아스카 주식 계좌 하루에 15만원씩 느는데 [4] 아스카영원히사랑해갤로그로 이동합니다. 09.05 91 0
2886903 뉴프로에서 베라 아이스크림 받아가라 이기 [1] 헬마스터갤로그로 이동합니다. 09.05 68 0
2886902 SI 파견가서 하는 프로젝트 수준이 어느정도임? [2] 프갤러(106.101) 09.05 83 0
2886900 냥덩이가 먹어도 되는 인간음식들❤+ ♥냥덩이♥갤로그로 이동합니다. 09.05 38 0
2886899 냥덩이는 자유민주주의의 상징임 ㅇㅅㅇ⭐ ♥냥덩이♥갤로그로 이동합니다. 09.05 59 0
2886898 멍유 자꾸 나님께 무례하게 깝죽거리지마라 [1] ♥냥덩이♥갤로그로 이동합니다. 09.05 70 0
2886895 이재명 실망임 [2] 프갤러(175.208) 09.05 70 2
2886894 냥덩이의 더럽고 추악한 실태 [4] 개멍청한유라갤로그로 이동합니다. 09.05 74 0
2886893 헤르미온느의 실체;; [2] ♥냥덩이♥갤로그로 이동합니다. 09.05 77 0
2886892 애플 이벤트 D - 5 ㅇㅅㅇ 헤르 미온느갤로그로 이동합니다. 09.05 36 0
2886891 태연 ㅇㅅㅇ 헤르 미온느갤로그로 이동합니다. 09.05 29 0
2886890 하루 한 번 헤르미온느 찬양 헤르 미온느갤로그로 이동합니다. 09.05 52 0
2886889 강아지 이 사진 어때보여? [1] 메쿠이료갤로그로 이동합니다. 09.05 60 0
2886888 엔지니어 아무대나 갖다 붙이는게 좀 빡침 [3] 루도그담당(58.239) 09.05 84 0
2886887 전략과 일정 ♥냥덩이♥갤로그로 이동합니다. 09.05 46 0
2886886 즐거운 목요일 아침~ 가연아갤로그로 이동합니다. 09.05 31 0
2886885 인지과학조져라 손발이시립디다갤로그로 이동합니다. 09.05 58 0
2886833 CPU 클럭 안 오르는 것마냥 AI도 10년 내로 멈출거임 [3] 프갤러(106.241) 09.05 119 0
2886832 섹스톤 재산이 14억이 넘던데 개발로 번거임??그럼 개발할게 뒷통수한방(1.213) 09.05 95 0
2886831 돈은 결국 노력이 아니다 타이밍 한방 통수다 ㅇㅇ 뒷통수한방(1.213) 09.05 51 0
2886830 일단 파이썬이나 JS나 개발 언어는 아님 [1] 프갤러(106.241) 09.05 108 0
2886829 돈이 최고다 [1] 아스카영원히사랑해갤로그로 이동합니다. 09.05 89 0
2886828 ai 사실상 버블 아님? [4] 프갤러(220.94) 09.05 122 0
2886826 언리얼, 백엔드 공부 해놓으면 다른분야 가도 쓸데 있음? [4] 프갤러(14.40) 09.04 101 0
2886823 이경규 왜 아직도 방송 나옴? [2] 야옹아저씨갤로그로 이동합니다. 09.04 85 0
2886822 온다냥.. 온다냥.. ♥냥덩이♥갤로그로 이동합니다. 09.04 46 0
2886821 퇴근하고 집에오면 사이드프로젝트하기 힘드네 XLM갤로그로 이동합니다. 09.04 47 0
2886820 나 오늘 6개월만에 점프런티 48개함 ㅇㅅㅇ ㅇㅇ(223.39) 09.04 50 0
2886818 요즘 재명이가 하는짓이랑 똑같넹 ♥냥덩이♥갤로그로 이동합니다. 09.04 66 0
2886815 논리회로 대신 희망회로를 돌려라 By 나님 ♥냥덩이♥갤로그로 이동합니다. 09.04 51 0
2886814 이번에 RAG에 LLM과 무관한 문서넣는 것만으로도 성능향상이 이루어진다 ㅆㅇㅆ(124.216) 09.04 75 0
2886813 리버싱 하다 벽 느껴서 [2] 루도그담당(58.239) 09.04 98 0
2886812 요즘 좆본 zenn.dev 보다보면서 느끼는 ㅆㅇㅆ(124.216) 09.04 62 0
2886811 나 근데 롤 지워야겠다. 가끔 롤체하는데 이씨발 뱅가드가 [5] ㅆㅇㅆ(124.216) 09.04 93 0
2886810 커널 패치가드 조작하다가 [2] 루도그담당(58.239) 09.04 68 0
2886809 mapper 패턴 예시 줌 [2] ㅆㅇㅆ(124.216) 09.04 89 1
2886808 내가 문제를 잘못이해했노. 그럼 expect/actual 쓰면되지 [1] ㅆㅇㅆ(124.216) 09.04 73 1
2886807 나님 누엇어양⭐+ ♥냥덩이♥갤로그로 이동합니다. 09.04 76 0
2886805 문제를 단순하게 만드셈 ㅇㅇ [7] ㅆㅇㅆ(124.216) 09.04 107 1
2886803 요새 si 회사 신입 연봉이 어케댐? [2] 프갤러(210.99) 09.04 130 0
2886800 어떤 산업에 종사한다는거랑 그 산업계를 이해하는건 다른거당 ♥냥덩이♥갤로그로 이동합니다. 09.04 83 0
2886799 저 아래 댓글에 대한 답 ㅆㅇㅆ(124.216) 09.04 64 2
2886797 가을님 오셨습니깡? ♥냥덩이♥갤로그로 이동합니다. 09.04 41 0
2886796 21세기는 인류는 진화해야한다 뒷통수한방(1.213) 09.04 51 0
뉴스 ‘이혼’ 홍진경 “다 맞춰주는 부부, 건강한 관계 아냐” 디시트렌드 09.06
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2