디시인사이드 갤러리

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

갤러리 본문 영역

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

ㅆㅇㅆ(124.216) 2025.08.08 10:17:06
조회 38 추천 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/08/04 - -
AD 가전디지털, 휴대폰 액세서리 SALE 운영자 25/08/08 - -
2879396 이유나 기자한테 따지다가 얼굴이 약간 일본 할아버지 에서 아저씨 느낌인데 넥도리아(223.38) 08.08 28 0
2879395 김건희가 워너비로 삼은 사람들 4인 발명도둑잡기갤로그로 이동합니다. 08.08 37 0
2879394 성향 검사 사이트 이런거 광고수익 얼마나 나올까 [1] 프갤러(49.142) 08.08 34 0
2879393 그나저나민생지원쿠폰12만으로뭐사지 [2] 현무E공인(211.234) 08.08 38 0
2879391 러스트 담론을 해체하다: 기술 토론에서 관찰되는 논증 오류 사례 분석 나르시갤로그로 이동합니다. 08.08 36 0
2879390 러스트 담론을 해체하다: 머리말 나르시갤로그로 이동합니다. 08.08 22 0
2879389 살아보니 학력이 발목을 많이잡는것같음 [2] ㅇㅇ(118.235) 08.08 64 0
2879387 2020년컴공졸업하고취업후6년시간개빠르네 현무E공인(211.234) 08.08 79 0
2879386 [애니뉴스] 텍스트엔진 해상도 비교 [1] 프갤러(121.172) 08.08 26 0
2879385 리팩토링 할 때마다 UX가 달라진다 순수400갤로그로 이동합니다. 08.08 32 0
2879384 빨리 퇴근하고싶다 ㅇㅇ(211.36) 08.08 18 0
2879383 방통대 다니는 직장인이 많네? [2] 루도그담당(118.235) 08.08 71 0
2879382 내년이면어느덧나도7년차개발자 현무E공인(211.234) 08.08 51 0
2879381 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥냥덩이♥갤로그로 이동합니다. 08.08 22 0
2879380 러스트 담론 해체하기"로 "새로운 삼대장" 반박하기 나르시갤로그로 이동합니다. 08.08 39 0
2879376 남은 연차 ㅁㅌㅊ? [1] 어린이노무현갤로그로 이동합니다. 08.08 53 0
2879375 요즘연애율떨어져서모솔도더이상이상한게아닌듯? 현무E공인(211.234) 08.08 49 0
2879373 나님 메접이욤 ㅇㅅㅇㅋㅋ 꼬깃꼬깃 흙묻은 아이템 파는중ㅋㅋ ㅇㅇ(223.39) 08.08 18 0
2879370 토실토실 큼직한 냥덩이 팝니당❤+ [2] ♥냥덩이♥갤로그로 이동합니다. 08.08 45 0
2879369 솔직히 말이 퀀트 투자지 실제로 돈벌려면 HFT 해야하는데 [3] ㅆㅇㅆ(124.216) 08.08 77 0
2879368 최원종 사건 재현 예감 발명도둑잡기갤로그로 이동합니다. 08.08 39 0
2879367 퀀트 프로그래밍이라는게 생각보다 복잡하거든. ㅆㅇㅆ(124.216) 08.08 46 0
2879364 금연이 날 정신병자로 만든다 프갤러(61.79) 08.08 33 0
2879363 전업 외주하면서 느끼는게 웹 유지보수 아니면 일거리가 잘 없음. [3] ㅆㅇㅆ(124.216) 08.08 85 0
2879362 프갤에서 봤던 애 중에 제일 같잖았던 새끼 [5] 프갤러(118.218) 08.08 84 3
2879361 외주 시장 남의 코드 기막힌거보고 느낀게 [6] ㅆㅇㅆ(124.216) 08.08 89 0
2879360 용산 나간다 할머니 용띠였다. 넥도리아(223.38) 08.08 29 0
2879359 함 점검 다녀와야겟넹 ♥냥덩이♥갤로그로 이동합니다. 08.08 22 0
2879358 흠.. ♥냥덩이♥갤로그로 이동합니다. 08.08 23 0
2879357 공공이나 금융에서 시스템하나 좆도아닌거 만드는데 몇억식 [4] 밀우갤로그로 이동합니다. 08.08 65 0
2879356 코인 그래프는 보면 볼수록 겨겨(211.234) 08.08 27 0
2879355 가방 6만원 글 보니 생각나는 예전 글 발명도둑잡기갤로그로 이동합니다. 08.08 17 0
2879354 섹스 ♥냥덩이♥갤로그로 이동합니다. 08.08 28 0
2879353 차명거래의 가장 큰 문제는 바로 가상화폐와 달러다 [3] 발명도둑잡기갤로그로 이동합니다. 08.08 40 0
2879352 고객사ㅜ파견 sm 인데 [4] theidh(211.234) 08.08 57 0
2879351 동학운동과 21세기 발명도둑잡기갤로그로 이동합니다. 08.08 17 0
2879350 모솔탈출강의보는데번호따기부터시작이네 현무E공인(211.234) 08.08 56 0
2879348 6년차32살연봉3500개발자금요일업무시작 [2] 현무E공인(211.234) 08.08 126 0
2879347 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥냥덩이♥갤로그로 이동합니다. 08.08 22 0
2879345 단점을 줄이고 장점을 늘린다. 별로 좋아하지 않는 말임. 프갤러(218.154) 08.08 30 0
2879344 민생지원금12만원남았는디 2차지급까지 버텨야지 현무E공인(211.234) 08.08 30 0
2879343 재테크강좌 Show me the money-> the liberty 발명도둑잡기갤로그로 이동합니다. 08.08 20 0
2879342 [대한민국][충격] 미 국무부 고위 직원, 미 주한 대사관 근무자 프갤러(121.172) 08.08 19 0
2879340 구글 수수료 정책 진짜 개좆같네 ㄹㅇ [1] 뉴진파갤로그로 이동합니다. 08.08 35 0
2879339 전세계 냥덩이들이여 일제히 봉기하라❤+ ♥냥덩이♥갤로그로 이동합니다. 08.08 24 0
2879338 장난쳤다가 일 존나 커짐 ㅋㅋㅋㅋㅋㅋ ㅇㅇ(211.234) 08.08 46 3
2879335 4 + 1 컴퓨존 주문했습니다. 입금도 했습니다. 점심시간에 죄송합니다 도리스아(220.74) 08.08 31 0
2879334 스톨만의 프로그래밍 언어 호불호 언급 발명도둑잡기갤로그로 이동합니다. 08.08 29 0
2879333 안철수도 러스트 프로그래밍한다고함 ㅋ 뒷통수한방(1.213) 08.08 51 0
2879332 한미일영 코메디의 가장 큰 문제는 아무리 적나라하게 웃기고 풍자를 해도 발명도둑잡기갤로그로 이동합니다. 08.08 23 0
뉴스 한혜연, 16kg 감량 이후 44kg 체중 유지하는 특별 비법 공개...“53세 몸매 맞아?” 디시트렌드 10:00
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2