디시인사이드 갤러리

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

갤러리 본문 영역

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

ㅆㅇㅆ(124.216) 2025.08.08 10:17:06
조회 64 추천 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/11 - -
AD 가전디지털, 휴대폰 액세서리 SALE 운영자 25/08/08 - -
2879764 다음생이 있으면 참새도 좋으니 새로 태어나고싶다 [1] 뒷통수한방(1.213) 08.09 62 0
2879763 토스 코테를 목표로 스터디 하는 것은 무리인 듯 프갤러(110.13) 08.09 165 0
2879762 책 쓰는게 프밍보다 어렵구나 나르시갤로그로 이동합니다. 08.09 53 0
2879759 냥덩이 조직적 스토킹, 도청 당한다고 주장 발명도둑잡기갤로그로 이동합니다. 08.09 52 0
2879757 잊지마 [1] ♥냥덩이♥갤로그로 이동합니다. 08.09 75 0
2879751 나는조현병이야 나는내향적이야 손발이시립디다갤로그로 이동합니다. 08.09 54 0
2879750 클로드(코드아님)은 어떰? 프갤러(221.167) 08.09 50 0
2879749 나님 암 걸린둣.. [5] ♥냥덩이♥갤로그로 이동합니다. 08.09 80 0
2879748 대 ai 시대에 교육 컨텐츠로 사업하시는 분들 [2] 헬마스터갤로그로 이동합니다. 08.09 80 0
2879743 창남창녀조차 못해서 욕하는 조센진들 [6] 개멍청한유라갤로그로 이동합니다. 08.09 87 0
2879741 아 피곤해 [3] 루도그담당(58.239) 08.09 60 0
2879740 멍청하고 역겨운 조센징들 개멍청한유라갤로그로 이동합니다. 08.09 62 0
2879738 확실한데도 조심스럽게 말하는것 [8] 헬마스터갤로그로 이동합니다. 08.09 92 1
2879726 나님 요즘 길냥덩들한테 조직적 스토킹,도청 당하는듯..? [1] ♥냥덩이♥갤로그로 이동합니다. 08.09 126 0
2879724 존나 머싯당.. ♥냥덩이♥갤로그로 이동합니다. 08.09 63 0
2879723 국비 9 월 vs 3 월. 물어 본 사람한테 쓰는 글. 프갤러(59.16) 08.09 124 0
2879721 왜 사람들이 신작 욕하는지 이해가 가긴가넹 전작이 넘 ㅆㅅㅌㅊ ♥냥덩이♥갤로그로 이동합니다. 08.09 47 0
2879718 전생에 무슨짓을햇길래 남좇센에서 태어났으까 뒷통수한방(1.213) 08.09 56 0
2879717 gto 너ㅁ 잼써 ♥냥덩이♥갤로그로 이동합니다. 08.09 56 0
2879716 국민의힘 갤러리 수급자 준봉이, 포함 기초차상위 디스견 [1] 도리스아넥도리아(220.74) 08.09 55 0
2879713 토스 코테 챗티씨5 1분컷아님? 헬마스터갤로그로 이동합니다. 08.09 188 0
2879711 갤에 토스 시험 다들 합격하렴. [2] ㅆㅇㅆ(124.216) 08.09 145 0
2879710 나님 낼 뛰뛰해야징❤+ ♥냥덩이♥갤로그로 이동합니다. 08.09 56 0
2879709 나는 외주땜시 nest.js 공부중 [2] ㅆㅇㅆ찡갤로그로 이동합니다. 08.09 78 0
2879707 토스 코테 보통 어느정도 해야함? [3] 프갤러(211.234) 08.09 236 0
2879705 토스가 시험봄? [2] ㅆㅇㅆ찡갤로그로 이동합니다. 08.09 154 0
2879704 아오 토스 [2] 밀우갤로그로 이동합니다. 08.09 141 0
2879703 퇴사 후 취업 너무 안되서 국비라도 들어보려고 함 [2] ㅇㅇ(118.235) 08.09 219 0
2879701 보통 회사에서 개발자 몇 년차부터 PL 맡김? [5] ㅇㅇ(118.235) 08.09 88 0
2879700 피아노도 취미로 괜찮은거같군요 현무E공인(58.225) 08.09 69 0
2879699 토스 next 시험봤는데 [4] 프갤러(110.13) 08.09 235 0
2879698 와..시간.. 프갤러(106.102) 08.09 108 0
2879696 나님 힐링즁⭐+ ♥냥덩이♥갤로그로 이동합니다. 08.09 51 0
2879690 <여행을 대신 해드립니다> 한대서 생각나는 예전 글 발명도둑잡기갤로그로 이동합니다. 08.09 58 0
2879688 속보지는 겉보지는 ♥냥덩이♥갤로그로 이동합니다. 08.09 68 0
2879685 <파인: 촌뜨기들> 예고편 발명도둑잡기갤로그로 이동합니다. 08.09 99 0
2879681 아버지 밑에서 일, 일주일 프갤러(121.172) 08.09 67 0
2879678 파인 임수점 발명도둑잡기갤로그로 이동합니다. 08.09 51 0
2879674 7 0 0 0 0원 받'으'세'요~~~ ㅇㅇ(106.101) 08.09 41 0
2879673 철이와 미애-너는 왜 발명도둑잡기갤로그로 이동합니다. 08.09 41 0
2879670 냥덩이 연예인 포르노 매매 이제는 안하지? 발명도둑잡기갤로그로 이동합니다. 08.09 49 0
2879669 내일배움카드가 발명도둑잡기갤로그로 이동합니다. 08.09 47 0
2879668 토스 코테 뭐냐 ㅇㅇ(218.155) 08.09 224 2
2879667 컨디션 조절이 가장 어려움 ♥냥덩이♥갤로그로 이동합니다. 08.09 47 0
2879665 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥냥덩이♥갤로그로 이동합니다. 08.09 49 0
2879642 박원-All of my life 발명도둑잡기갤로그로 이동합니다. 08.09 36 0
2879637 노션 띄어쓰기 어케함 [1] 프갤러(112.146) 08.09 63 0
2879628 내일배움카드로 개발자 부트캠에서 배우고싶은데 추천부탁드립니다 프갤러(61.254) 08.09 72 0
2879624 나님께 나쁜말 악플 ㄴㄴ ♥냥덩이♥갤로그로 이동합니다. 08.09 54 0
2879616 최.초.공.개 ♥냥덩이♥갤로그로 이동합니다. 08.09 59 0
뉴스 '스트릿 캐주얼 편집샵' 바운더리(BOUNDARY), ’K-핫플레이스’ 성수동에 첫 플래그십 스토어 오픈 디시트렌드 08.16
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2