디시인사이드 갤러리

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

갤러리 본문 영역

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

ㅆㅇㅆ(124.216) 2025.08.08 10:17:06
조회 94 추천 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 - -
2881409 그 약이라는게 그렇게 끊기가 힘듬?? 계속 생각나?? [1] ㅇㅇ(223.39) 08.14 163 0
2881408 개발이 근데 그렇게 힘듬? [3] 프갤러(106.101) 08.14 160 0
2881407 시골 터미널 ㅇㅅㅇ [1] 헤르 미온느갤로그로 이동합니다. 08.14 124 0
2881406 태연 ㅇㅅㅇ 헤르 미온느갤로그로 이동합니다. 08.14 73 0
2881405 하루 한 번 헤르미온느 찬양 헤르 미온느갤로그로 이동합니다. 08.14 131 0
2881404 AI 가 답해주는 포럼 웹사이트 만듬 프갤러(211.55) 08.14 104 0
2881402 게임 1인 개발 성공하니까 단나더 생각나네 ㅇㅇ(125.182) 08.14 192 1
2881400 게임개발하고싶어서 컴공 진학 희망하는 학생인데 진짜 궁금한거 있음. [15] 프갤러(58.78) 08.14 264 0
2881399 패턴 템플릿을 만들어두고 세부 구현 주의사항을 제네릭하게 만들어서 [1] ㅆㅇㅆ(124.216) 08.14 137 0
2881397 시스템 명세 짜고 설명붙이고 구현하고 ㅆㅇㅆ(124.216) 08.14 130 0
2881396 하루 평균 클래스 40개의 명세, 함수, 메서드 약 200개여개 명세 [1] ㅆㅇㅆ(124.216) 08.14 147 0
2881381 근데 개발자 취업시장 안좋은건 [23] 프갤러(118.235) 08.14 768 0
2881370 참 공부를 하면서 느낀다 루도그담당(58.239) 08.14 111 0
2881369 프갤에 글이 없네 ㅋㅋ [2] 프갤러(121.139) 08.14 140 1
2881368 냉면 먹어야겠다 ㄱ ㅐ ㅆ ㅣ빨썌끼들아!!!!!! 프갤러(121.139) 08.14 90 0
2881365 납품 준비 하나 끝. 아 존나 힘들다 ㅆㅇㅆ(124.216) 08.14 92 0
2881351 개인적으로 개발 세부 구현사항은 문서화 안하지만 전반적으로 ㅆㅇㅆ(124.216) 08.14 125 0
2881348 그리고 기본적으로 마소 예제는 나름대로 기술 분석 해두는게 좋더라 [2] ㅆㅇㅆ(124.216) 08.14 170 0
2881347 뇌과학적으로 고소득층 사람들은 물건보다 '이것'에 집착합니다 발명도둑잡기갤로그로 이동합니다. 08.14 91 0
2881346 아인슈타인의 ‘그 논문’ 50년간 묻혔다가 과학계 레전드로 역주행 발명도둑잡기갤로그로 이동합니다. 08.14 124 0
2881345 나는 대부분 내가 만들어보거나 해본 것들 어지간하면 적어둠 [8] ㅆㅇㅆ(124.216) 08.14 160 0
2881344 나는 크롤링 전문이 아니라서, 그냥 기초 원리만 아는거. [3] ㅆㅇㅆ(124.216) 08.14 156 0
2881343 아씨발나스닥왜자꾸올라개새끼야!!!!!!! [3] 아스카영원히사랑해갤로그로 이동합니다. 08.14 141 0
2881342 웹 크롤링 뷰티풀 스프 사용하는 방법 [2] ㅆㅇㅆ(124.216) 08.14 136 0
2881341 나도 어제 좆개판으로 크롤러 짯는데 [2] 루도그담당(58.239) 08.14 146 0
2881340 R 스크립트 짜면서 느끼는데 유독 파이썬 R은 GPT가 잘짜 ㅆㅇㅆ(124.216) 08.14 118 0
2881338 개발 항상 하면 느끼지만 가장 큰 적은 '돌아가는데 굳이..' 이거임 [2] ㅆㅇㅆ(124.216) 08.13 136 0
2881337 그 약이라는게 그렇게 끊기가 힘듬?? 계속 생각나?? [7] ㅇㅇ(223.39) 08.13 183 0
2881336 파이썬 질문있습니다 [3] 프갤러(211.105) 08.13 146 0
2881335 ㅆㅇㅆ님 이 글에 대해 의견좀 [1] 발명도둑잡기갤로그로 이동합니다. 08.13 143 0
2881331 내가 ai 안쓰는 이유 프갤러(121.139) 08.13 149 0
2881330 금융 로직의 문제는 뭐냐면 [1] 밀우갤로그로 이동합니다. 08.13 175 0
2881327 프갤러들 제국주의자 되는 과정 발명도둑잡기갤로그로 이동합니다. 08.13 114 0
2881326 이직했는데 존나어렵다 [1] 프갤러(220.70) 08.13 201 0
2881324 코테 문제들 어질어질하노 [1] 프갤러(220.85) 08.13 438 0
2881321 ㅇㅣ거 뭐냐 ㅇㅇ(211.105) 08.13 84 0
2881317 요즘 식당, 술집들 보면 술로 너무 폭리 취함 [19] 야옹아저씨갤로그로 이동합니다. 08.13 482 6
2881315 챗티씨에 코드 맡기고 나는 누워잇는중 [1] 헬마스터갤로그로 이동합니다. 08.13 133 0
2881312 도대체 영화관리를 어떻게 하길래 벌써 XX티비에 영화가 다떴지?? [6] ㅇㅇ(223.39) 08.13 151 0
2881309 잡코리아에서 AI 공모전으로 채용까지 하네요 프갤러(114.203) 08.13 96 0
2881302 퍼플렉시티랑 지피티 듀오로 가야하나 프갤러(61.79) 08.13 105 0
2881300 빌게이츠 이새낀 좇센 왜오는거?? 미국에선 총기맞을까봐 오는거?? 타이밍뒷통수한방(1.213) 08.13 107 0
2881297 카페 와이파이를 쓰면 안 되는 이유 발명도둑잡기갤로그로 이동합니다. 08.13 132 0
2881294 리눅스 예전에는 좋았던거 같은데 점점 성능이 내려가는느낌임 타이밍뒷통수한방(1.213) 08.13 110 0
2881292 형님들 엑셀 도움좀 주실분요 ㅠㅠ [1] 프갤러(180.69) 08.13 122 0
2881291 다들 웹사이트 만들 때 폰트 뭐 씀? ㅇㅇ갤로그로 이동합니다. 08.13 97 0
2881286 러스트가 확실히 요증 대세는 맞네 ㅇㅇ(125.179) 08.13 129 0
2881284 asp.net core 문서 보면서 공부나 해야겠다 루도그담당(58.239) 08.13 106 0
2881283 나도 MCP 만들어서 쓰는데 굳이 한국 토종 MCP 써야할 무언가인가 [4] ㅆㅇㅆ(124.216) 08.13 159 0
2881280 카카오 MCP 나옴 [1] 프갤러(121.133) 08.13 153 0
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

디시미디어

디시이슈

1/2