디시인사이드 갤러리

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

갤러리 본문 영역

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

ㅆㅇㅆ(124.216) 2025.08.08 10:17:06
조회 44 추천 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 - -
2879685 <파인: 촌뜨기들> 예고편 발명도둑잡기갤로그로 이동합니다. 08.09 70 0
2879683 마귀 소굴을 지키는 것도 질렸어요. 프갤러(220.84) 08.09 44 0
2879681 아버지 밑에서 일, 일주일 프갤러(121.172) 08.09 41 0
2879678 파인 임수점 발명도둑잡기갤로그로 이동합니다. 08.09 27 0
2879674 7 0 0 0 0원 받'으'세'요~~~ ㅇㅇ(106.101) 08.09 27 0
2879673 철이와 미애-너는 왜 발명도둑잡기갤로그로 이동합니다. 08.09 20 0
2879670 냥덩이 연예인 포르노 매매 이제는 안하지? 발명도둑잡기갤로그로 이동합니다. 08.09 29 0
2879669 내일배움카드가 발명도둑잡기갤로그로 이동합니다. 08.09 26 0
2879668 토스 코테 뭐냐 ㅇㅇ(218.155) 08.09 188 2
2879667 컨디션 조절이 가장 어려움 ♥냥덩이♥갤로그로 이동합니다. 08.09 25 0
2879665 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥냥덩이♥갤로그로 이동합니다. 08.09 26 0
2879650 xx진과 xx우와의 추억은 바보짓이었습니다. 프갤러(220.84) 08.09 34 0
2879642 박원-All of my life 발명도둑잡기갤로그로 이동합니다. 08.09 20 0
2879640 가려해도 어딜간단 말이지요? 프갤러(220.84) 08.09 34 0
2879637 노션 띄어쓰기 어케함 [1] 프갤러(112.146) 08.09 39 0
2879628 내일배움카드로 개발자 부트캠에서 배우고싶은데 추천부탁드립니다 프갤러(61.254) 08.09 30 0
2879625 영혼이 튀겨지는 고통입니다. 프갤러(220.84) 08.09 37 0
2879624 나님께 나쁜말 악플 ㄴㄴ ♥냥덩이♥갤로그로 이동합니다. 08.09 29 0
2879618 고통스럽네요. 어떡하라는 겁니까. 프갤러(220.84) 08.09 36 0
2879616 최.초.공.개 ♥냥덩이♥갤로그로 이동합니다. 08.09 37 0
2879615 함부로 다른 ip에 핑보내면 처벌받냐? [2] 프갤러(118.223) 08.09 67 0
2879614 [대한민국] 법왜곡죄와 사법권의 남용 및 대처 방안에 관한 연구 프갤러(121.172) 08.09 19 0
2879613 처음부터 불청객이었지요. 프갤러(220.84) 08.09 31 0
2879612 토스 공채 이번에 역대급이긴 함 3만명 지원했음 [2] 프갤러(121.167) 08.09 162 0
2879611 ‘착한 사나이’ 문태유, 짧지만 강한 존재감! ‘신스틸러’ 활약 기대 발명도둑잡기갤로그로 이동합니다. 08.09 30 0
2879610 디씨 매물로 나왔데 프갤러(110.47) 08.09 38 0
2879609 나 중요부위 제모중인데 아이스팩으로 열식히면서 피부 염증 넥도리아(220.74) 08.09 30 0
2879608 해외주식이랑 선물, 옵션에 API가 유료라 ㅆㅇㅆ(124.216) 08.09 31 0
2879607 흠.. ♥냥덩이♥갤로그로 이동합니다. 08.09 25 0
2879606 해외주식, 해외선물 등등 이게 분야가 왜 세부적으로 다르지 ㅆㅇㅆ(124.216) 08.09 28 0
2879600 잼땅 ♥냥덩이♥갤로그로 이동합니다. 08.09 28 0
2879598 세상이 나를 부르는것 같습니다. 프갤러(220.84) 08.09 39 0
2879596 에구구.. ♥냥덩이♥갤로그로 이동합니다. 08.09 35 0
2879590 좆소ㄹㅈㄷ네 [4] 프갤러(175.223) 08.09 91 0
2879588 중요 부위 제모의 중요성 특유 냄새 제거 가능 넥도리아(220.74) 08.09 38 0
2879586 한국에서 살아가는법 프갤러(61.79) 08.09 33 0
2879577 마귀소굴의 진상은 외국에까지 퍼져야합니다. 프갤러(220.84) 08.09 38 0
2879572 말로는 프로그래밍 방법론 전문가 [2] ㅇㅇ(211.234) 08.09 93 5
2879571 인간의 삶이 버거워요. 프갤러(220.84) 08.09 44 0
2879569 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥냥덩이♥갤로그로 이동합니다. 08.09 25 0
2879564 엄마 초심 잃었는데 어떻게 된거냐 야발 ㅇㅅㅇ... [1] ㅇㅇ(223.39) 08.09 54 0
2879556 [속보]관세문제 해결 안됬다 한국경제 최악의 리스크 2찢명 ♥냥덩이♥갤로그로 이동합니다. 08.09 44 0
2879555 개발자는 디지털 사법고시다 프갤러(106.101) 08.09 60 0
2879553 시발 존나무서운 요즘 초딩 6학년 근황ㄷㄷ.jpg ㅇㅇ(113.192) 08.09 98 0
2879551 검은 잠자리..ㅇㅅㅇ 헤르 미온느갤로그로 이동합니다. 08.09 60 0
2879550 태연 ㅇㅅㅇ 헤르 미온느갤로그로 이동합니다. 08.09 40 1
2879549 하루 한 번 헤르미온느 찬양 헤르 미온느갤로그로 이동합니다. 08.09 54 0
2879548 면식없는 자들에게 어찌 도움을 기대하겠어요. 프갤러(220.84) 08.09 38 0
2879541 깨어있는자는 나뿐인가.. 현무E공인(58.225) 08.09 43 0
2879536 오후9시취침 새벽4시기상 미라클모닝 시작 현무E공인(58.225) 08.09 55 0
뉴스 ‘혼외자 인정’ 김병만 전처 딸 파양 “무고 패륜행위” 디시트렌드 08.09
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2