디시인사이드 갤러리

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

갤러리 본문 영역

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

ㅆㅇㅆ(124.216) 2025.08.08 10:17:06
조회 89 추천 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/06 - -
AD 프로게이머가 될테야!! 운영자 25/10/01 - -
2880446 불가족천민 이민자 받은 캐나다 근황 ㄹㅇ [1] ♥냥덩이♥갤로그로 이동합니다. 08.11 140 0
2880445 근데 내가 중국인이라도 [1] 아스카영원히사랑해갤로그로 이동합니다. 08.11 110 0
2880444 안철수 “이재명은 매국노” ♥냥덩이♥갤로그로 이동합니다. 08.11 97 0
2880443 퇴근하고 집에 갑니다 루도그담당(118.235) 08.11 84 0
2880442 갑질옹호 좌파 유시민 논란 ♥냥덩이♥갤로그로 이동합니다. 08.11 102 0
2880441 근데 GPT 2년동안 발전한거 코드 품질이 발전한거지 ㅆㅇㅆ(124.216) 08.11 114 0
2880440 KT 장애냐? ㅇㅇ(118.235) 08.11 96 0
2880439 존나 별거없는 프로그래밍 관련 업적 [1] ㅇㅇ(106.101) 08.11 142 0
2880438 애널의달성 2.1/1/ ♥냥덩이♥갤로그로 이동합니다. 08.11 82 0
2880436 으악 타입스크립트 애니 역겹다. 프갤러(218.154) 08.11 108 0
2880435 본인 ai 그림 개발자 될려고 공부중임 [2] ㅇㅇ(106.102) 08.11 130 0
2880434 필연적 구조 논리로 미래를 예견하당 By 나님 ♥냥덩이♥갤로그로 이동합니다. 08.11 83 0
2880433 퇴근 얼마 안남았다 루도그담당(118.235) 08.11 97 0
2880431 KiiiKiii 키키 'DANCING ALONE' 발명도둑잡기갤로그로 이동합니다. 08.11 84 0
2880430 AI가 우리 몰래 비밀언어를 쓴다... 는 것보다 소름끼치는 현 연구결과 발명도둑잡기갤로그로 이동합니다. 08.11 89 0
2880429 특이점 온다 노동해방시대 온다 ㅇㅇ 뒷통수한방(1.213) 08.11 89 0
2880428 긴급] 길냥덩 쥐찢명 잡는 영상 최초 공개 !! ♥냥덩이♥갤로그로 이동합니다. 08.11 91 0
2880427 적당한 추상화는 이해에 도움되는데 [2] 루도그담당(118.235) 08.11 131 0
2880426 GOT7(갓세븐) "A" 발명도둑잡기갤로그로 이동합니다. 08.11 87 0
2880425 나님 스스로에 대해 더 잘 알아야행 ♥냥덩이♥갤로그로 이동합니다. 08.11 90 0
2880424 이게 추상화 계층 레이어가 나뉘어져있다는 이해가 있으면 존나 편함 [3] ㅆㅇㅆ(124.216) 08.11 110 0
2880423 프로그래밍 설계하면서 중요한 청사진은 문법으로 구현되지 않음. ㅆㅇㅆ(124.216) 08.11 114 0
2880421 프로그래밍 아키텍트의 장점이 언어에 구애를 안받음 [2] ㅆㅇㅆ찡갤로그로 이동합니다. 08.11 90 0
2880420 영웅의 여정 발명도둑잡기갤로그로 이동합니다. 08.11 65 0
2880419 프로도: "이런 일이 내 시대에 일어나지 않았더라면 좋았을 텐데요." 발명도둑잡기갤로그로 이동합니다. 08.11 78 0
2880418 개발자란 직업 나만 멋있어보임? [4] 프갤러(211.60) 08.11 165 0
2880417 집정리하다 나온 먼지 덮인 ‘이것’···경매서 9000만원에 팔렸다는데 발명도둑잡기갤로그로 이동합니다. 08.11 79 0
2880416 지피티이거 웹에서 루도그담당(118.235) 08.11 91 0
2880415 젊은애들이 힘든일 안 하려는 이유 발명도둑잡기갤로그로 이동합니다. 08.11 92 0
2880414 지피티 글 삭제도 좀 이상하지 않냐 [1] 프갤러(61.79) 08.11 88 0
2880413 챗지피티는 5나오고나서 애가 더 멍청해진거같네 [2] 공기역학갤로그로 이동합니다. 08.11 132 0
2880412 애초에 마소는 이미 자기네들 홈페이지 완성 예시 다 올려뒀잖아 [3] ㅆㅇㅆ(124.216) 08.11 123 0
2880410 "소고기 사먹을 줄 알았더니"…소비쿠폰 풀리자 대박 난 '이곳' 발명도둑잡기갤로그로 이동합니다. 08.11 82 0
2880409 마소가 만들어논거보면 좋은 점이 [1] 루도그담당(118.235) 08.11 104 0
2880408 특이점 온다 노동해방시대 온다 ㅇㅇ 뒷통수한방(1.213) 08.11 80 0
2880407 Asp.net core 이거 존나 좋은데 [2] 루도그담당(118.235) 08.11 131 0
2880405 내가 프갤에 있는 이유)여기 조차도 안가면 이야기할 곳이 없다 [2] ㅆㅇㅆ(124.216) 08.11 120 0
2880403 적어도 프로그래밍 업종은 중국애들이 시민의식이 더 높음. [2] ㅆㅇㅆ(124.216) 08.11 111 0
2880402 유독 프로그래밍 업계라는 애들이 톡시하지 않냐? [2] ㅆㅇㅆ(124.216) 08.11 110 2
2880401 40대부터는 사업을 하고 싶다 프갤러(61.79) 08.11 90 0
2880400 번식한새끼들은 대우해주는거 아무리봐도 이해 좇나 안가네 뒷통수한방(1.213) 08.11 89 0
2880399 Asp.net core는 왜 안 쓰는거냐 루도그담당(118.235) 08.11 106 0
2880398 gpt5.0때문에 오늘 두시간 날렸네 프갤러(175.210) 08.11 102 0
2880397 댓글 이쁘게 발명도둑잡기갤로그로 이동합니다. 08.11 91 0
2880396 이기적인 놈 응용 좆되노 이기 [1] 슈퍼막코더(126.194) 08.11 124 0
2880395 2찢명 운지 스타또⭐+ ♥냥덩이♥갤로그로 이동합니다. 08.11 92 0
2880394 개발자 목메지마라 ♥냥덩이♥갤로그로 이동합니다. 08.11 96 0
2880393 아이 구해주는 코끼리 발명도둑잡기갤로그로 이동합니다. 08.11 76 0
2880392 챗지피티같은 이미지 생성기 만드는거 어려움? ㅇㅇ(106.102) 08.11 87 0
2880391 한국인이 시골에 친척끼리 같이 살던 문화라 남과 비슷해지려 발명도둑잡기갤로그로 이동합니다. 08.11 82 0
뉴스 “스태프가 ‘XX 싸가지 없는 애’라고” 자폭한 남자연예인 디시트렌드 10.08
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2