디시인사이드 갤러리

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

갤러리 본문 영역

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

ㅆㅇㅆ(124.216) 2025.08.08 10:17:06
조회 72 추천 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/25 - -
이슈 느린 여행으로 삶의 속도를 찾는 유튜버 꾸준 운영자 25/08/26 - -
2883678 러스트 쓰면 안 되는 이유 나르시갤로그로 이동합니다. 08.23 32 0
2883676 서버 방식 다국어 IME 만들 줄이나 아냐? 나르시갤로그로 이동합니다. 08.23 40 0
2883675 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥냥덩Art♥갤로그로 이동합니다. 08.23 34 0
2883674 청년세대가 극좌 기득권에 분노하는 이유 ♥냥덩Art♥갤로그로 이동합니다. 08.23 39 0
2883673 친중매국 이재명 때문에 IMF 경제공항 오는즁;; [2] ♥냥덩Art♥갤로그로 이동합니다. 08.23 53 0
2883672 ㅋㅅㅋ ♥냥덩Art♥갤로그로 이동합니다. 08.23 28 0
2883671 끙야기운 오다가셧당 ♥냥덩Art♥갤로그로 이동합니다. 08.23 30 0
2883670 물로켓 시절에 ime 하나 만든거 가지고 벗어나질 못하는구나. [2] 프갤러(110.8) 08.23 65 0
2883668 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥냥덩Art♥갤로그로 이동합니다. 08.23 44 0
2883667 ㄹㅇ 요즘 짱깨 맛 없더라 ♥냥덩Art♥갤로그로 이동합니다. 08.23 41 0
2883665 피해자없길바란다 프갤러(211.253) 08.23 56 0
2883664 이종각 ㅇㅅㅇ 헤르 미온느갤로그로 이동합니다. 08.23 43 0
2883663 태연 ㅇㅅㅇ 헤르 미온느갤로그로 이동합니다. 08.23 36 0
2883662 하루 한 번 헤르미온느 찬양 헤르 미온느갤로그로 이동합니다. 08.23 50 0
2883661 플머의 유일한 장점은 국가에 제한받지 않는다는거 아니겟냐 공기역학갤로그로 이동합니다. 08.23 48 0
2883660 Ada와 Rust는 그 점에서 흥미로운 대조 나르시갤로그로 이동합니다. 08.23 46 0
2883659 착 달라붙는 흰 티 입은 여자들 볼때마다 예쁘네 메쿠이로갤로그로 이동합니다. 08.23 57 0
2883658 프외자 이사람 ㄹㅇ 진짜 인생이 궁금함 ㅇㅇ(211.176) 08.23 84 0
2883657 도미노피자 예약 주문햇다 야옹아저씨갤로그로 이동합니다. 08.23 69 0
2883655 외국년 소주먹이고 반응 ㅇㅇ ㅇㅇ(58.229) 08.23 81 0
2883653 r&d예산 세계최고 또 증액 경재성장률은 씹운지 ㅋㅋㅋㅋ 뒷통수한방(1.213) 08.23 34 0
2883651 아마 2026년즘 Ada로 만든 Nimf 출시 예정이시다 나르시갤로그로 이동합니다. 08.23 42 0
2883649 IME(입력기)도 아키텍쳐가 얼마나 중요한데 [1] 나르시갤로그로 이동합니다. 08.23 55 0
2883647 역시 러스트로는 대규모 플젝 못해 나르시갤로그로 이동합니다. 08.23 52 0
2883646 뭐 대단한거 만든다고 아키텍처를 따지냐? 대충 해라 [1] 프갤러(110.8) 08.23 77 0
2883645 음기 충전 발명도둑잡기갤로그로 이동합니다. 08.23 40 0
2883644 좋은 일본노래 듣고갑시다 프로외노자갤로그로 이동합니다. 08.23 55 0
2883642 제 조립 릴스 보심? 방금 인스타그램. 넥도리아(223.38) 08.23 35 0
2883641 아키텍쳐 설계는 기술보단 노하우임 에이도비갤로그로 이동합니다. 08.23 48 0
2883640 초보가 가장 많이 격는 노드 에러 정리 프갤러(121.133) 08.22 51 0
2883639 그냥 달리고 걸어... 재활용. [1] 넥도리아(223.38) 08.22 54 0
2883637 구름 뭐냐 그냥 연기지. 넥도리아(222.233) 08.22 41 0
2883636 요즘 술 안먹는사람들 존나 많아진듯 ㅇㅅㅇ 유전자가 약해졌나 ㅇㅇ(124.60) 08.22 51 0
2883635 ㅆㅇㅆ이랑 술마시고 싶다 [5] 아스카영원히사랑해갤로그로 이동합니다. 08.22 137 0
2883634 일이 다 일이지 그냥 돈벌이여 프갤러(61.79) 08.22 41 0
2883633 개발 어느정도 짬 먹은 애들은 [7] 루도그담당(58.239) 08.22 123 0
2883631 컴공애들 존나불쌍하네 [2] ㅇㅇ(223.38) 08.22 126 0
2883627 헬조센에선 헬조센대로 생존법이 있다 프갤러(61.79) 08.22 42 0
2883626 컴퓨터랑 섹스하시기 위해 [1] 루도그담당(58.239) 08.22 61 0
2883625 여자랑 이야기 해본지 약 9년전 [4] ㅆㅇㅆ(124.216) 08.22 98 0
2883624 근데 확실히 LLM 쓰기 시작하면서 아키테쳐적으로 시각이 바뀜 [4] ㅆㅇㅆ(124.216) 08.22 104 0
2883623 유튜브댓글에 수학으로 선민사상 느끼는 놈들 많네 [2] ㅇㅇ(106.102) 08.22 66 0
2883622 아키텍쳐에 정답은 없고 그순간의 답이 있을뿐 [3] ㅆㅇㅆ(124.216) 08.22 97 0
2883621 firebase studio 덕분에 갤럭시10울트라로 개발 쉬워짐... 프갤러(121.128) 08.22 73 0
2883620 밑에 아키텍쳐 논쟁 딱 알려준다 [3] ㅆㅇㅆ(124.216) 08.22 90 0
2883619 넥슨 이 새끼들 소름이구나 루도그담당(58.239) 08.22 78 0
2883617 회사에서 아키텍쳐 설계 논쟁 있었는데 [16] 프갤러(39.117) 08.22 173 0
2883616 요 최근에 부업으로 바이브 코더들 구현 막힌거 고쳐주면서 사는데 [2] ㅆㅇㅆ(124.216) 08.22 89 0
2883615 중국인에게 전하는 말 프갤러(211.234) 08.22 42 0
2883614 날 더워가 뛰뛰를 제대로 못하니 살 찐당 ♥냥덩Art♥갤로그로 이동합니다. 08.22 70 0
뉴스 기안84도 경악…이세희 ‘곰팡이 지갑‘에 깜짝 “몸이 가려워져” 디시트렌드 08.25
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2