디시인사이드 갤러리

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

갤러리 본문 영역

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

ㅆㅇㅆ(124.216) 2025.08.08 10:17:06
조회 93 추천 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/10/13 - -
2879298 빈부격차 심한 사회에서 적은 사회보다 인기 많은 노래 특징 발명도둑잡기갤로그로 이동합니다. 08.08 91 0
2879295 118.235 발명도둑잡기갤로그로 이동합니다. 08.08 90 0
2879294 지피티 류 코드의 문제점이 메모리를 한번에 올려 자꾸 ㅆㅇㅆ(124.216) 08.08 84 0
2879293 휴대용 레트로 콘솔 게임기 KNULLI 운영체제 부팅 스크린 발명도둑잡기갤로그로 이동합니다. 08.08 80 0
2879292 지피티 5 코드 전반적으로 맥락에 따른 코드 변화를 미묘하게 못잡아낸다. ㅆㅇㅆ(124.216) 08.08 79 0
2879291 왜 펌웨어랑 윈도우는 커서같은 툴이안나오는것임? 네오커헠(211.234) 08.08 109 0
2879290 지피티 5 써보는데 여전히 소스제네레이터보다 리플랙션쓰네 [1] ㅆㅇㅆ(124.216) 08.08 112 0
지피티 5로 코드 뱉어봤는데 여전히 좀 아쉽 ㅆㅇㅆ(124.216) 08.08 93 0
2879288 용산을 일주일에 1번은 기본으로 가네요. 도리스아(220.74) 08.08 96 0
2879287 왜 윾과장은 메시지를 쳐안읽는 걸까요? [1] 아스카영원히사랑해갤로그로 이동합니다. 08.08 91 0
2879285 자바는 뭔가 일하고있다는 표시를 내는 언어임 [2] ㅇㅇ갤로그로 이동합니다. 08.08 118 0
2879283 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥냥덩이♥갤로그로 이동합니다. 08.08 75 0
2879282 GPT-5가 좋은 게 뭐냐면 [1] 에이도비갤로그로 이동합니다. 08.08 134 0
2879281 gpt5.0 써봉사람들 평이 먼가 그저그런데? [2] 밀우갤로그로 이동합니다. 08.08 156 0
2879280 5가 여태 나온 모델 짬뽕해서 넣은건가 [3] 루도그담당(211.184) 08.08 105 0
2879278 지피티는 코드성능 별론거같은데 [4] ㅆㅇㅆ(124.216) 08.08 113 0
2879276 뭐냐 5 나왔네 루도그담당(211.184) 08.08 98 0
2879273 즐거운 목요일 아침입니다~ [5] 가연아갤로그로 이동합니다. 08.08 93 0
2879272 정신력 전성기를 맞이하고있는거같음 [4] 공기역학갤로그로 이동합니다. 08.08 100 0
2879271 옹해내로 외계인공식화 될수도? ♥냥덩이♥갤로그로 이동합니다. 08.08 86 0
2879270 tiobe 인덱스는 병신 지표이며 pypl이 더 정확합니다. 프갤러(218.154) 08.08 101 0
2879268 GPT5 성능 진짜 좆된다 [3] 에이도비갤로그로 이동합니다. 08.08 176 1
2879267 나 이기적인 사람이야. 이웃 생각하면서 타인생각하면서도 가족한테는 넥도리아(220.74) 08.08 76 0
2879266 샌도니거 인도인들은 다 쫓아내야한다 ♥냥덩이♥갤로그로 이동합니다. 08.08 82 0
2879265 한녀는 악성재고다 [4] ♥냥덩이♥갤로그로 이동합니다. 08.08 97 0
2879261 오늘나온 뉴스인데 엄청 공감가네 [2] 에이도비갤로그로 이동합니다. 08.08 311 1
2879260 이 한남새끼들아 이 내가 힘들다고 하잖아! ㅇㅇ(211.246) 08.08 86 0
2879259 개발자는 가망없고 보안은 가망있는듯 [1] 프갤러(175.208) 08.08 182 0
2879258 나님 통찰력 왤케 ㅆㅅㅌㅊ일깡? ♥냥덩이♥갤로그로 이동합니다. 08.08 93 0
2879257 상대방의 외모가 자신이 생각한 자기의 외모에 가까울수록 [1] ♥냥덩이♥갤로그로 이동합니다. 08.08 95 0
2879256 치욕스러워서, 굴욕적이어서 살지 못하겠습니다. [1] 프갤러(220.84) 08.08 118 1
2879255 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥냥덩이♥갤로그로 이동합니다. 08.08 84 0
2879254 발언권, 결정권, 영향력 박탈하니까 뒤집어지죠. 프갤러(220.84) 08.08 107 0
2879253 빈부격차 심한 사회에서 적은 사회보다 인기 많은 노래 특징 발명도둑잡기갤로그로 이동합니다. 08.08 87 0
2879251 귀신, 신, 유령이 하나도 안 무서워지게 되는 방법 발명도둑잡기갤로그로 이동합니다. 08.08 99 0
2879250 힙합-合(합할 합, 홉 갑, 홉 홉)-SEX-X-처형-십자가-십-씹 발명도둑잡기갤로그로 이동합니다. 08.08 70 0
2879249 생물학 대인 무기 약물: 정상인에게 조현병 걸리게 하는 약 성분 발명도둑잡기갤로그로 이동합니다. 08.08 171 0
2879244 권위주의와 종교와 성적 억압 발명도둑잡기갤로그로 이동합니다. 08.08 157 0
2879242 쉿! ♥냥덩이♥갤로그로 이동합니다. 08.08 81 0
2879232 어케 act에서 떨어지지 ㅅㅂ 프갤러(175.112) 08.08 155 0
2879222 자바가 개병신인 이유 [1] ㅇㅇ갤로그로 이동합니다. 08.08 130 0
2879220 근데 왜 아직도 국비지원 << 왤케 해주는거임? [3] 프갤러(222.107) 08.08 366 0
2879217 부서에 트롤있으면 코드 개 ㅈ되냐? 프갤러(118.223) 08.08 100 0
2879216 자야겠어 루도그담당(58.239) 08.08 87 0
2879215 오늘의 소설, 영화 실마리: 밤에는 고양이 낮에는 개로 변하는 사람 발명도둑잡기갤로그로 이동합니다. 08.08 91 0
2879212 형들 재택근무가 많은 개발직종은 어디야? [1] 프갤러(175.204) 08.07 158 0
2879210 헬조센에선 정신과 약 먹으며 버티는게 답이다 프갤러(61.79) 08.07 98 0
2879208 마음을 비우면 행복해져요~ [3] 개멍청한유라갤로그로 이동합니다. 08.07 116 0
2879205 아스카는 내일 휴가다 [2] 아스카영원히사랑해갤로그로 이동합니다. 08.07 134 0
2879204 진동스피커가 책상에 납땜 되었습니다. 순간접착제 들어가서, ㅠㅠㅠ 넥도리아(220.74) 08.07 76 0
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

디시미디어

디시이슈

1/2