디시인사이드 갤러리

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

갤러리 본문 영역

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

ㅆㅇㅆ(124.216) 2025.08.08 10:17:06
조회 104 추천 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/11/03 - -
AD 저녁 뭐먹지? 오늘의 메뉴 추천! 운영자 25/10/31 - -
2884237 라디오를 소재로 한 영화 발명도둑잡기갤로그로 이동합니다. 08.25 98 0
2884233 Interstella 5555: The 5tory of the 5ecre 발명도둑잡기갤로그로 이동합니다. 08.25 107 0
2884231 누가 더 유명함 팝스타 축구선수 [2] 디바(59.28) 08.25 183 0
2884230 요즘 마틴 파울러나 켄트벡 전부 AI 워크플로우 통합 강의하고 다녀서 [1] ㅆㅇㅆ(124.216) 08.25 136 0
2884229 일단 내일은 오랜만에 시간 여유가 있으니 프갤에 CS글이나 쓰고 ㅆㅇㅆ(124.216) 08.25 115 0
2884228 AI 코딩을 안하면 프리로써 못 살아남음 요즘 프리 하나 완성 가격 [2] ㅆㅇㅆ(124.216) 08.25 195 0
2884223 AI를 쓰면서 느끼는 장점과 단점 [5] ㅆㅇㅆ(124.216) 08.25 209 0
2884221 친구가 너무 언더도그마의 화신같은 존재라 말이안나옴 [4] 공기역학갤로그로 이동합니다. 08.25 161 0
2884219 책을보면 개발할시간이없고 개발하면 책을뵬시간이없구나 [4] 밀우갤로그로 이동합니다. 08.25 159 0
2884218 https://www.queup.net/ 간이 침투검사 결과 발명도둑잡기갤로그로 이동합니다. 08.25 112 0
2884216 흉드라 팀뷰어 자꾸 끈겨.... 좀 도와줘 어케 뚫어요?? ㅠㅠ ㅇㅇ(59.25) 08.25 102 0
2884209 공무원이 짱이다 주4.5일제도입, 월급인상 ㅇㅇ(211.193) 08.24 232 0
2884205 프로그래밍 이론 책 읽다보면 여전히 아는게 부족하다 [2] ㅆㅇㅆ(124.216) 08.24 148 0
2884204 조언을 구하고 싶습니다 [4] 프갤러(121.45) 08.24 188 0
2884203 Floating Points - Silhouettes I, II and 발명도둑잡기갤로그로 이동합니다. 08.24 93 0
2884202 영어잘하냐 ㅇㅇ(58.229) 08.24 120 0
2884200 ‘포스트 박찬욱 봉준호’는 정말 없나 [라제기의 슛 & 숏] 발명도둑잡기갤로그로 이동합니다. 08.24 107 0
2884197 C++ 인생 40 년 갈아 넣었습니다. 프갤러(59.16) 08.24 120 0
2884195 코딩은 그냥 it분야의 1%임 ㅇㅇ갤로그로 이동합니다. 08.24 143 0
2884193 너드면 보안와라 [1] ㅇㅇ갤로그로 이동합니다. 08.24 184 0
2884191 외계인이 지구를 침략하면 아마겟돈이 가장 손 쉬움 [1] ♥지나가던냥덩이♥갤로그로 이동합니다. 08.24 152 0
2884189 “라식 없이 1분 만에 시력 교정”…전류로 각막 성형 성공 [1] 발명도둑잡기갤로그로 이동합니다. 08.24 157 0
2884188 나님 플롯 생각낫는데 예전에 어디서본듯한;; ♥지나가던냥덩이♥갤로그로 이동합니다. 08.24 119 0
2884186 ㅇㅅㅇ⭐+ ♥지나가던냥덩이♥갤로그로 이동합니다. 08.24 93 0
2884185 꽁꽁냥덩이는 어또케 집냥덩이 됫을까? ♥지나가던냥덩이♥갤로그로 이동합니다. 08.24 136 0
2884184 나님 다음닉 뭘로할깡.. [3] ♥지나가던냥덩이♥갤로그로 이동합니다. 08.24 125 0
2884182 '버스, 정류장' 예고편 발명도둑잡기갤로그로 이동합니다. 08.24 139 0
2884179 한투증 api쓰려면 계좌만들어야함?ㅋㅋ [1] 밀우갤로그로 이동합니다. 08.24 111 0
2884176 요새 유행인 Golden... 발명도둑잡기갤로그로 이동합니다. 08.24 108 0
2884167 ㅇㅅㅇ ♥지나가던냥덩이♥갤로그로 이동합니다. 08.24 102 0
2884165 영어회화 공부해볼까 해서 공기역학이 광고하던 VRCHAT 가입했다 [1] 발명도둑잡기갤로그로 이동합니다. 08.24 122 0
2884163 뉴프로라는 새로운 IT 커뮤니티 나왔더라 [2] 헬마스터갤로그로 이동합니다. 08.24 138 0
2884162 harha - 매스커레이드 [1] 발명도둑잡기갤로그로 이동합니다. 08.24 108 0
2884160 내일 잼난일 많을듯 ㅎㅅㅎ ♥지나가던냥덩이♥갤로그로 이동합니다. 08.24 115 0
2884154 왜 나님이 쓰는글 계속 모니터링 하는거에양? ♥지나가던냥덩이♥갤로그로 이동합니다. 08.24 116 0
2884151 태국기 맞잖아요 [1] 발명도둑잡기갤로그로 이동합니다. 08.24 136 0
2884144 "SNS까지 뒤져본다"…美 거주·취업 때 반미 정서 심사 발명도둑잡기갤로그로 이동합니다. 08.24 99 0
2884143 내 인생목표 현실적으로 이룰 수 있으려나? [2] ㅇㅇ(58.229) 08.24 186 0
2884138 ㄴㅏ님 주무시기전 소통⭐+ 질문 받음☘+ ♥지나가던냥덩이♥갤로그로 이동합니다. 08.24 94 0
2884130 태극기가 국기면 태국기라고 해야 되는거 아닌가요? [1] 발명도둑잡기갤로그로 이동합니다. 08.24 125 0
2884128 웹앱땔깜애들 요즘 걍 측은지심으로바뀜 [1] 네오커헠(58.225) 08.24 203 1
2884127 언어 프레임워크 강함 순위 [2] 프갤러(106.101) 08.24 203 0
2884126 저장용 ♥지나가던냥덩이♥갤로그로 이동합니다. 08.24 91 0
2884122 트럼프 모바일 첫 스마트폰 근황 발명도둑잡기갤로그로 이동합니다. 08.24 111 0
2884119 나님 애널 일찍 주무실게양❤+ ♥지나가던냥덩이♥갤로그로 이동합니다. 08.24 122 0
2884118 요즘도 코테로 사람 걸러내나요? [1] ㅇㅇ갤로그로 이동합니다. 08.24 243 0
2884115 [애니뉴스][잡지] 오후우와 이야기의 핵심에 다가가는 해설 프갤러(121.172) 08.24 87 0
2884114 노조법 개정안 국회 통과, 하청 노동자도 원청과 교섭한다 발명도둑잡기갤로그로 이동합니다. 08.24 94 0
2884113 고언어 어디까시 성장할거같음? [1] 프갤러(125.179) 08.24 121 0
2884112 재개발 언제 하려낭 ♥지나가던냥덩이♥갤로그로 이동합니다. 08.24 103 0
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

디시미디어

디시이슈

1/2