디시인사이드 갤러리

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

갤러리 본문 영역

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

ㅆㅇㅆ(124.216) 2025.08.08 10:17:06
조회 63 추천 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 - -
2880783 난 일자리 없다는말 못믿겟던데 프갤러(106.101) 08.12 56 0
2880782 단순 퍼블리싱속도면 C#윈폼이 웹개발떡바름 네오커헠(58.225) 08.12 70 0
2880780 개발자는 의사들처럼 파업안하냐 [5] 프갤러(125.182) 08.12 181 1
2880779 범죄자 윤미향 위안부할머니들 돈 횡령 반환 안해 ♥냥덩이♥갤로그로 이동합니다. 08.12 76 0
2880778 냥덩세컨드!!! ♥냥덩이♥갤로그로 이동합니다. 08.12 44 0
2880777 점저는 컨디션 일정따라 무겁게도 가볍ㄱ도 ♥냥덩이♥갤로그로 이동합니다. 08.12 36 0
2880776 아침은 가볍게라도 꼭 머거야함 ♥냥덩이♥갤로그로 이동합니다. 08.12 46 0
2880775 게임엔진 없이 게임 개발 <<< 진짜 먹히는 프로젝트냐 [3] 민뚜색갤로그로 이동합니다. 08.12 88 0
2880774 이거 진짜 맛잇음 ♥냥덩이♥갤로그로 이동합니다. 08.12 36 0
2880772 나 이번이 막학기인데 진짜 취업 ㅈ된 듯... [2] ㅇㅇ(58.235) 08.12 102 0
2880771 백엔드 개발은 일종의 쿠팡물류창고같은거임 [1] 네오커헠(58.225) 08.12 112 0
2880769 코테 문제 사이트 요즘 뭐가 좋아? [3] ㅇㅇ갤로그로 이동합니다. 08.12 252 0
2880768 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥냥덩이♥갤로그로 이동합니다. 08.12 36 0
2880767 나님 왤케 특별한걸깡? ♥냥덩이♥갤로그로 이동합니다. 08.12 40 0
2880766 윈도우ui개발에서 중요한건 xaml같은 퍼블리싱이아님 네오커헠(211.234) 08.12 81 0
2880765 김건희를 보면 한녀들의 표독한 뒷모습을 알 수 있다 [5] 아스카영원히사랑해갤로그로 이동합니다. 08.12 94 0
2880763 프갤 글젠이 처참하군요 [5] 루도그담당(211.184) 08.12 78 0
2880762 자러 감 잇다바 바바이~ ㅇㅅㅇ// 헤르 미온느갤로그로 이동합니다. 08.12 33 0
2880761 요즘 asp.net도 vscode로 가르치더라 [4] 헬마스터갤로그로 이동합니다. 08.12 92 0
2880759 다리 몰카.ㅇㅅㅇ [1] 헤르 미온느갤로그로 이동합니다. 08.12 58 0
2880758 요즘 신입들 실력 어떰? [4] ㅇㅇ갤로그로 이동합니다. 08.12 164 0
2880757 태연 ㅇㅅㅇ 헤르 미온느갤로그로 이동합니다. 08.12 37 0
2880756 하루 한 번 헤르미온느 찬양 헤르 미온느갤로그로 이동합니다. 08.12 41 0
2880754 위안부 할머니들을 등쳐먹은 범죄자 극좌 윤미향 ♥냥덩이♥갤로그로 이동합니다. 08.12 60 0
2880753 얘들아 깃헙 기여부탁행 [1] (119.202) 08.12 72 0
2880752 국제범죄조직 짱깨에 영혼을 판 친짱매국좌파들 ♥냥덩이♥갤로그로 이동합니다. 08.12 43 0
2880734 선선하구낭 ♥냥덩이♥갤로그로 이동합니다. 08.12 37 0
2880715 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥냥덩이♥갤로그로 이동합니다. 08.12 44 0
2880703 Ada 프로그래밍 명저를 만들 겁니다. [1] 나르시갤로그로 이동합니다. 08.12 64 0
2880699 원점으로 되돌아가 Ada 책 목차 작성부터 다시하고 있습니다. 나르시갤로그로 이동합니다. 08.12 43 0
2880689 Ada 프로그래밍: 4.2.6 고급 반복자: 간략한 개요 [1] 나르시갤로그로 이동합니다. 08.12 85 0
2880687 Ada 프로그래밍: 4.2.5 병렬 루프 (Ada 2022) 나르시갤로그로 이동합니다. 08.12 75 0
2880685 Ada 프로그래밍: 4.2.4 루프 이름짓기 나르시갤로그로 이동합니다. 08.12 44 0
2880683 Ada 프로그래밍: 4.2.3 for 루프 나르시갤로그로 이동합니다. 08.12 80 0
2880678 vscode가 심각한 버그가 많구나 나르시갤로그로 이동합니다. 08.12 67 0
2880667 GPT 5 모델도 아첨이 너무 심하다 [1] ㅆㅇㅆ(124.216) 08.12 77 0
2880633 노트북으론 대규모 프로젝트 빌드가 안되네 프갤러(58.29) 08.12 55 0
2880602 라이브러리 만들었는데 평가해줄 프갤형 구함 프갤러(222.233) 08.12 74 3
2880601 와 생활비 다떨어졌는데 석사 논문 그래프 의뢰 겨우 받았다 ㅆㅇㅆ(124.216) 08.12 67 0
2880583 서울대 10개 만들기 한국대학교 서울 제 1 대학교 매머드 캠퍼스!# 프갤러(168.126) 08.12 78 1
2880580 개발자에게 정신병은 훈장과같다 [1] ㅇㅇ(211.234) 08.12 64 0
2880577 코테 준비하려면 어케 해야 하나? 프갤러(211.177) 08.12 292 0
2880565 그까짓 이유는 자바를 깔 이유가 못됩니다 [1] 박민준갤로그로 이동합니다. 08.12 102 0
2880562 근데 프로그래밍 하다보면 어차피 남도 잘 모르고 나도 잘 몰라서 [1] ㅆㅇㅆ(124.216) 08.12 97 0
2880559 블로그 쓰다보면 겸허해짐 [4] 박민준갤로그로 이동합니다. 08.11 105 0
2880548 애초에 MSA의 서비스는 도메인 단위의 독립 애플리케이션을 뜻함 [7] ㅆㅇㅆ(124.216) 08.11 120 0
2880546 애새끼들이 흔히 착각하는게 MSA의 서비스와 서비스 레이어의 서비스는 ㅆㅇㅆ(124.216) 08.11 73 0
2880545 요즘 중국에 대해 공부 중이다 [6] 아스카영원히사랑해갤로그로 이동합니다. 08.11 108 0
2880541 항상 느끼지만 타스, 자스는 npm 빌드가 너무 힘들다 ㅆㅇㅆ(124.216) 08.11 59 0
2880521 asp.net core 사용중이시다. [2] 루도그담당(58.239) 08.11 66 0
뉴스 장원영, 논란의 시축 의상 사진 올리며 당당히 대응...“아이브 유니폼 짱 귀엽지? 디시트렌드 08.15
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2