디시인사이드 갤러리

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

갤러리 본문 영역

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

ㅆㅇㅆ(124.216) 2025.08.08 10:17:06
조회 80 추천 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/09/08 - -
AD 신학기 레벨업~!! 운영자 25/09/05 - -
2887409 [대한민국] '왜 좌파하세요'의 답 - 사이트 업데이트 네이버 블로그 연 프갤러(121.172) 09.07 24 0
2887408 인도네시아 누리꾼들이 한글로 소통하는 까닭은 발명도둑잡기(118.216) 09.07 21 0
2887407 다람쥐도 쥐로 취급함? [4] 메쿠이료갤로그로 이동합니다. 09.07 61 0
2887406 스스로를 죽이고 싶을만큼 삶 앞에 무력하고 힘이들때. ㅇㅇ(223.38) 09.07 27 0
2887404 아이디어 하나 더 생각났는데 어떰? [5] ㅇㅇ갤로그로 이동합니다. 09.07 50 0
2887403 ✨진격의냥덩 1화⭐ ♥뽀송냥덩♥갤로그로 이동합니다. 09.07 29 0
2887402 새삼 트럼프 빅테크 모아놓고 회의한 거랑 전승절이랑 프갤러(211.210) 09.07 30 0
2887400 병신들아 버스 안에서 야동 보지 마라 [2] 아스카영원히사랑해갤로그로 이동합니다. 09.07 94 0
2887399 오늘 점심.jpg [2] 야옹아저씨갤로그로 이동합니다. 09.07 53 0
2887380 나는 돈벌게되면 일 제대로 못할듯 체력이 없음 이제 뒷통수한방(1.213) 09.07 22 0
2887379 김정은이 똑똑한건 인정해야지 [2] 야옹아저씨갤로그로 이동합니다. 09.07 53 0
2887378 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥냥덩의태양은밤에도빛난당♥갤로그로 이동합니다. 09.07 25 0
2887377 영어 할 줄 아세요? ㅇㅅㅇ 헤르 미온느갤로그로 이동합니다. 09.07 40 0
2887376 파이썬 기초부터 초보입문자가 쉽게 배울수 있는 책 있나요? [3] 프갤러(223.39) 09.07 49 0
2887375 애플 이벤트 D - 3 ㅇㅅㅇ [1] 헤르 미온느갤로그로 이동합니다. 09.07 34 0
2887374 태연 ㅇㅅㅇ 헤르 미온느갤로그로 이동합니다. 09.07 26 0
2887373 하루 한 번 헤르미온느 찬양 헤르 미온느갤로그로 이동합니다. 09.07 50 0
2887372 취미로 프로그래밍(코딩) 배우고 싶은데... [14] 프갤러(223.39) 09.07 92 0
2887366 인지과학조져라 손발이시립디다갤로그로 이동합니다. 09.07 60 0
2887355 빌 게이츠가 직접 만든건 컴파일러인거임?? [1] ㅇㅇ(211.62) 09.07 68 0
2887352 됐다 완전한 RAG 만들었다. [1] ㅆㅇㅆ(124.216) 09.07 95 0
2887346 입천장 데였나봄 [1] 루도그담당(58.239) 09.07 44 0
2887344 보통 웹에서 선형대수 쓰는건 이런거 만들어. 내가 만든거 보여줌 [1] ㅆㅇㅆ(124.216) 09.07 81 0
2887343 여사친 어카냐 블개갤로그로 이동합니다. 09.07 56 0
2887340 솔직히 웹 UI 자신없어서 애니메이션 구현에 전력 때려박는중 [3] ㅆㅇㅆ(124.216) 09.07 82 0
2887337 귀염❤+ 소듕❤+ [6] ♥냥덩의태양은밤에도빛난당♥갤로그로 이동합니다. 09.07 61 0
2887336 결국 친중재명 때문이었네.. 외교대실패 회담결렬 ♥냥덩의태양은밤에도빛난당♥갤로그로 이동합니다. 09.07 48 0
2887334 음기 충전 발명도둑잡기(118.216) 09.07 79 0
2887332 이게 딥스가 아니면 누가 딥스라는거임? [6] 야옹아저씨갤로그로 이동합니다. 09.07 171 5
2887330 냥덩이 마누라 되실 분 발명도둑잡기(118.216) 09.07 29 0
2887328 전세계에서 한국만큼 살기좋은나라가 없다고???애미 씨발 노인씹새끼들아ㅋㅋ 뒷통수한방(1.213) 09.07 33 0
2887327 AI와 ‘야한 대화’에 빠진 초등생들... 학교는 안절부절 발명도둑잡기(118.216) 09.07 52 0
2887326 ㅋㅅㅋ ♥냥덩의태양은밤에도빛난당♥갤로그로 이동합니다. 09.07 32 0
2887324 애플 박스 심리 트릭 발명도둑잡기(118.216) 09.07 30 0
2887322 aice associate 땄는데 반도체러한텐 스펙안되나 프갤러(211.235) 09.07 38 0
2887321 친중재명 때문에 한국만 관세 25% ? ♥냥덩의태양은밤에도빛난당♥갤로그로 이동합니다. 09.06 31 0
2887320 언리얼 많이 어려움? [3] 뉴진파갤로그로 이동합니다. 09.06 45 0
2887319 재명이 때문에 트럼프가 몽둥이 들었넹 ♥냥덩의태양은밤에도빛난당♥갤로그로 이동합니다. 09.06 40 0
2887318 애들아 미안한데 내 만들고 있는 웹사이트 디자인좀 봐다오 [9] ㅆㅇㅆ(124.216) 09.06 121 0
2887317 “자본주의가 끝났다” 현재 미국을 뒤흔든 인텔 국유화 쇼크 [1] 발명도둑잡기(118.216) 09.06 92 0
2887316 속보) 광주에서 석유 발견 ㄷㅅㄷ ♥냥덩의태양은밤에도빛난당♥갤로그로 이동합니다. 09.06 46 0
2887315 더불어민쥬당 동성 성추행 ㄷㅅㄷ 게이임? ♥냥덩의태양은밤에도빛난당♥갤로그로 이동합니다. 09.06 31 0
2887314 더불어민쥬당 신종갑 여직원 감금 ㄷㅅㄷ ♥냥덩의태양은밤에도빛난당♥갤로그로 이동합니다. 09.06 34 0
2887313 호미들(Homies) - 완공 발명도둑잡기(118.216) 09.06 28 0
2887312 웹 개발할거면 쉐이더나 three.js 아니면 수학 쓸데 없지 않나 ㅆㅇㅆ(124.216) 09.06 42 0
2887311 라면먹고갈래? [5] 발명도둑잡기(118.216) 09.06 40 0
2887310 라면 먹고 갈래? 발명도둑잡기(118.216) 09.06 27 0
2887308 수학 열심히 팠으면 메리트 있는 분야가 어딘가요? [5] 프갤러(211.248) 09.06 71 0
2887306 지금 RAG를 닫힌 환경으로 했는데 이걸 제미나이 CLI랑 연동하고 싶데 ㅆㅇㅆ(124.216) 09.06 41 0
2887305 봄날은 간다. 라면먹을래... 라면먹고갈래의 원조 발명도둑잡기(118.216) 09.06 27 0
뉴스 암 투병 고백하더니 “참담하다”…‘박성광♥’ 이솔이 충격 근황 디시트렌드 09.07
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2