디시인사이드 갤러리

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

갤러리 본문 영역

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

ㅆㅇㅆ(124.216) 2025.08.08 10:17:06
조회 69 추천 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/18 - -
AD 전자제품 세일쇼! 운영자 25/08/19 - -
2880548 애초에 MSA의 서비스는 도메인 단위의 독립 애플리케이션을 뜻함 [7] ㅆㅇㅆ(124.216) 08.11 135 0
2880546 애새끼들이 흔히 착각하는게 MSA의 서비스와 서비스 레이어의 서비스는 ㅆㅇㅆ(124.216) 08.11 87 0
2880545 요즘 중국에 대해 공부 중이다 [6] 아스카영원히사랑해갤로그로 이동합니다. 08.11 122 0
2880541 항상 느끼지만 타스, 자스는 npm 빌드가 너무 힘들다 ㅆㅇㅆ(124.216) 08.11 74 0
2880521 asp.net core 사용중이시다. [2] 루도그담당(58.239) 08.11 79 0
2880517 이번에 nest.js로 서비스 여러개 묶어서 플랫폼 만드는거 의뢰받아서 [8] ㅆㅇㅆ(124.216) 08.11 126 0
2880516 자바는 일관성이 없는게 좆같음 루도그담당(58.239) 08.11 94 0
2880505 자바프로젝트 폴더 구시대의 닷컴버블의 잔재 아니냐? [2] 밀우갤로그로 이동합니다. 08.11 94 0
2880498 아래 대우 글 보니 드는 생각 발명도둑잡기갤로그로 이동합니다. 08.11 81 0
2880494 트럼프 경제안보 수탈 반대 1만인 선언 서명 발명도둑잡기갤로그로 이동합니다. 08.11 55 0
2880491 힙합 갤러리 작명 글 보니 드는 생각 발명도둑잡기갤로그로 이동합니다. 08.11 65 0
2880490 얼굴에 문신했던 20대男, 결국 다 지운 이유는? 발명도둑잡기갤로그로 이동합니다. 08.11 55 0
2880488 내가 자바를 극혐하는 이유. [3] 프갤러(59.16) 08.11 133 0
2880487 회사가 망해서 진짜 대리 운전 해야하네 ㅠㅠ [1] 프갤러(106.102) 08.11 110 0
2880485 아니 ㅅㅂ 대우 안한다 생각하면 ㅅㅂ 알아서 좀 잘해 프갤러(211.234) 08.11 135 0
2880484 아무에게도 방해받기 싫은 나님만의 소중한 시간⭐+ ♥냥덩이♥갤로그로 이동합니다. 08.11 49 0
2880482 경찰 '난동' 수사에 전광훈 "교회는 '가스라이팅'하는 곳" 발명도둑잡기갤로그로 이동합니다. 08.11 54 0
2880481 대만도 삼함회 ♥냥덩이♥갤로그로 이동합니다. 08.11 63 0
2880480 나님 동서양을 아우르는 글로벌인재?!? [1] ♥냥덩이♥갤로그로 이동합니다. 08.11 61 0
2880479 변태 냥덩이 발명도둑잡기갤로그로 이동합니다. 08.11 61 0
2880478 범죄자 명단 공개 ㄷㅅㄷ ♥냥덩이♥갤로그로 이동합니다. 08.11 52 0
2880477 대통령 놀이 하는놈부터가 범죄자 새끼니 이것 참;; ♥냥덩이♥갤로그로 이동합니다. 08.11 57 0
2880476 광복절 특별사면복권자 명단 발명도둑잡기갤로그로 이동합니다. 08.11 58 0
2880475 모모링한테 폭행 당하구 싶당.. ♥냥덩이♥갤로그로 이동합니다. 08.11 72 0
2880474 학벌이 뭔 소용이냐 [2] 프갤러(211.234) 08.11 105 0
2880473 빨리 이 나라 뜨고싶다. [1] 프갤러(211.57) 08.11 91 1
2880472 한녀 였다묜? ♥냥덩이♥갤로그로 이동합니다. 08.11 59 0
2880471 나님 예술세계는 우주급?!? ♥냥덩이♥갤로그로 이동합니다. 08.11 56 0
2880469 냥덩냥덩냥냥❤+ ♥냥덩이♥갤로그로 이동합니다. 08.11 60 0
2880468 선행은 말그대로 선의지 의무나 강요로 이루어 지는게 아니당 By 나님 ♥냥덩이♥갤로그로 이동합니다. 08.11 46 0
2880466 범죄자정권답게 악질 범죄자 사회에 풀어놓는 2찢명 ㄷㅅㄷ [3] ♥냥덩이♥갤로그로 이동합니다. 08.11 57 0
2880465 나님 일찍 주무십니당⭐+ ♥냥덩이♥갤로그로 이동합니다. 08.11 51 0
2880464 내가 느끼는게 트랜스포머 아키텍쳐로는 지금 이게 한계인거 같음 [1] ㅆㅇㅆ(124.216) 08.11 65 0
2880463 요즘 20대들은 쿵쿵따 모름? [2] ㅇㅇ(211.235) 08.11 73 2
2880462 특이점 온다 노동해방시대 온다 ㅇㅇ [2] 뒷통수한방(1.213) 08.11 66 1
2880461 외주의뢰가 없어서 돈이 없다 [3] ㅆㅇㅆ(124.216) 08.11 83 0
2880460 역시나 나님 방식이 맞았꾼 ㅋㅅㅋ ♥냥덩이♥갤로그로 이동합니다. 08.11 52 0
2880459 웹사이트 만들었는데 봐주실 분 있나요 [1] ㅇㅇ(106.241) 08.11 88 0
2880458 gpt는 갈수록 병신같아지네 프갤러(61.75) 08.11 73 1
2880457 러닝이조음 헬스가조음?? [1] 어린이노무현갤로그로 이동합니다. 08.11 79 0
2880456 이 세상은 나님을 위해 돌아가는걸까나앙~? ㅎㅅㅎ ♥냥덩이♥갤로그로 이동합니다. 08.11 61 0
2880455 풉킼 시대가 나님을 도와주는구낭 ㅋㅅㅋ ♥냥덩이♥갤로그로 이동합니다. 08.11 52 0
2880453 초등학생들 볼링 실력 발명도둑잡기갤로그로 이동합니다. 08.11 55 0
2880451 뛰뛰 후유증 2일째 ♥냥덩이♥갤로그로 이동합니다. 08.11 49 0
2880449 김상욱 "윤미향 '나쁜 사람' 생각했는데 알고보니 악마화 발명도둑잡기갤로그로 이동합니다. 08.11 75 0
2880448 또 물어뜯기는 윤미향…마용주 판사는 무슨 짓을 했나 발명도둑잡기갤로그로 이동합니다. 08.11 96 0
2880447 추미애 의원 <윤미향에 대하여 사법 왜곡한 마용주 판사> 발명도둑잡기갤로그로 이동합니다. 08.11 99 0
2880446 불가족천민 이민자 받은 캐나다 근황 ㄹㅇ [1] ♥냥덩이♥갤로그로 이동합니다. 08.11 86 0
2880445 근데 내가 중국인이라도 [1] 아스카영원히사랑해갤로그로 이동합니다. 08.11 68 0
2880444 안철수 “이재명은 매국노” ♥냥덩이♥갤로그로 이동합니다. 08.11 64 0
뉴스 '화려한 날들' 정인선, 사랑스러움 한도 초과! 섬세한 연기로 인간 비타민 지은오에 스며들었다! 디시트렌드 08.21
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2