디시인사이드 갤러리

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

갤러리 본문 영역

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

ㅆㅇㅆ(124.216) 2025.08.08 10:17:06
조회 96 추천 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 - -
AD iPad Pro 사전예약!! 운영자 25/10/17 - -
공지 프로그래밍 갤러리 이용 안내 [96] 운영자 20.09.28 48053 65
2897182 두순머신 ㄷㅅㄷ ♥덩냥이♥갤로그로 이동합니다. 08:05 7 0
2897181 반복적 죄수의 딜레마 게임에서 최강의 전략은? 발명도둑잡기(118.216) 07:52 7 0
2897178 국가보안법은 이성과 윤리체계를 붕괴시킨다 발명도둑잡기(118.216) 07:22 17 0
2897172 학점 질문 [5] 프갤러(118.235) 05:18 47 0
2897171 성인 콜라텍 충남 최고의 춤꾼! 배구공(119.202) 05:17 25 0
2897167 [인터뷰] 나원준 “트럼프 강요 계속되면 협상 깨도 국민 박수 칠 것” 발명도둑잡기(118.216) 04:49 25 0
2897166 [이태경의 토지와 자유] 이재명 정부 보유세 강화에 시동거나 발명도둑잡기(118.216) 04:44 17 0
2897165 유네스코유산 <니벨룽의 노래>, <니벨룽의 반지> 발명도둑잡기(118.216) 04:31 17 0
2897161 홈페이지 링크 클릭했다가 stream.ts라는 파일이 자동 다운 되었는데 프갤러(180.80) 04:14 26 0
2897160 반지의 제왕 소설에 영향 준 작품 발명도둑잡기(118.216) 04:06 23 0
2897158 가슴이 작으면 유방암 덜 걸리나 발명도둑잡기(118.216) 03:43 21 0
2897156 미친 존재감 발명도둑잡기(118.216) 03:37 18 0
2897155 <반지의 제왕> 예고편 발명도둑잡기(118.216) 03:34 22 0
2897154 진짜 학계는 존나 피곤한 곳이구나 한다. ㅆㅇㅆ(124.216) 03:13 50 0
2897151 웹툰 원작 넷플릭스 시리즈 '닭강정', 국제에미상 후보에 올라 발명도둑잡기(118.216) 03:08 18 0
2897149 알콜중독이다 시이발... 오늘은 내 안먹을라 켔는데 ㅇㅇ(223.39) 02:58 20 0
2897148 열이 내렸다 발명도둑잡기(118.216) 02:57 20 0
2897147 근데 MDPI가 그렇게 학계에서 평이 안좋나 ㅆㅇㅆ(124.216) 02:55 27 0
2897146 중국 애들 코드가 좋은게 중국애들은 ㅆㅇㅆ(124.216) 02:49 38 0
2897145 교수 구워 삶았다. 이제는 진짜 구현만 하면된다 ㅋㅋㅋ ㅆㅇㅆ(124.216) 02:46 28 0
2897144 LG G5 부팅 시켰거든요... 넥도리아20252024026(220.74) 02:25 29 0
2897143 나는 김치에 곰팡이 펴서 버렸는데 아래는 김치도 있구나 ㅇㅇ(175.197) 02:09 23 0
2897142 가난이 밉다... 밥에 김치뿐이 먹을게 없는 삶이 밉다... ㅇㅇ(223.39) 02:05 29 0
2897133 물경력이 얼마나 많으면 회사에서 믿지를 않아. [1] 프갤러(59.16) 00:03 68 0
2897132 남자 6명이서 캄보디아 여행가도 납치당함 ㅇㅅㅇ?? ㅇㅇ(223.39) 10.18 30 0
2897131 인천행 중국 여객기, 수하물 보조배터리 불로 상하이 비상착륙 발명도둑잡기(118.216) 10.18 28 0
2897128 Riverpod 3.0 나온거 실제 플젝에 적용한 사람 있어?? 프갤러(211.234) 10.18 27 0
2897125 음기 충전 발명도둑잡기(118.216) 10.18 52 0
2897122 집 와이파이 이상 발명도둑잡기(118.216) 10.18 24 0
2897117 세상에는 공짜란 것은 없다. (이상하다. 난...) 넥도리아(119.195) 10.18 30 0
2897116 오타니 미춋따 미춋어 ㄷㅅㄷ ♥덩냥이♥갤로그로 이동합니다. 10.18 42 0
2897115 나님 슬슬 주무실 준비 [2] ♥덩냥이♥갤로그로 이동합니다. 10.18 64 0
2897114 모모가 수상하당.. [3] ♥덩냥이♥갤로그로 이동합니다. 10.18 86 0
2897113 국산스파 [1] 배구공(119.202) 10.18 41 0
2897112 일 3건 취소. 매일매일 스트레스다 [4] ㅆㅇㅆ(124.216) 10.18 90 1
2897111 중미평화우호조약이란게 있는데 한중불가침평화협정도 맺으면 어떨까? [15] 발명도둑잡기(118.216) 10.18 66 0
2897109 미국은 금리가높은데 한국은 못올리니 환율이 오르는구나 [11] ㅇㅇ(175.197) 10.18 88 0
2897107 코딩 배우면 평생 먹구사나요? [3] 프갤러(218.54) 10.18 121 0
2897103 힛트가요 총맞은것처럼 [2] 배구공(119.202) 10.18 56 0
2897102 C++ 인생 40 년 갈아 넣었습니다. [1] 프갤러(59.16) 10.18 75 0
2897101 서울환경연합-버리는 도시 넘어, 고치는 도시로: 수리 활성화 조례안 설명 발명도둑잡기(118.216) 10.18 23 0
2897100 아침 점심 저녁 발명도둑잡기(118.216) 10.18 22 0
2897099 프갤에서도 카톡 업뎃 사건에 대한 논의가 있었겠지?? [2] chironpractor갤로그로 이동합니다. 10.18 56 0
2897098 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥덩냥이♥갤로그로 이동합니다. 10.18 26 0
2897097 강민호 어디로 가려낭 [3] ♥덩냥이♥갤로그로 이동합니다. 10.18 78 0
2897096 박병호는 은퇴해야하지 않낭 ♥덩냥이♥갤로그로 이동합니다. 10.18 62 0
2897095 문동주는 아무리봐도 지리넹 ㄷㅅㄷ ♥덩냥이♥갤로그로 이동합니다. 10.18 88 2
2897093 눈동자속의 faraway 남자 커버 배구공(119.202) 10.18 28 0
2897092 기아는 양현종 은퇴하면 더 안볼듯? ♥덩냥이♥갤로그로 이동합니다. 10.18 54 0
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

디시미디어

디시이슈

1/2