디시인사이드 갤러리

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

갤러리 본문 영역

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

ㅆㅇㅆ(124.216) 2025.08.08 10:17:06
조회 67 추천 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 - -
2881574 나님 깻당? ♥냥덩이♥갤로그로 이동합니다. 08.15 50 0
2881572 술 진탕 마셨는데 루도그담당(118.235) 08.15 56 0
2881571 음기 충전 발명도둑잡기갤로그로 이동합니다. 08.15 54 0
2881548 인터넷 거실 서 측정하는데 느린가요? [2] 넥도리아(220.74) 08.15 51 0
2881547 인터넷 거실 서 측정하는데 느린가요? [2] 넥도리아(220.74) 08.15 65 0
2881546 색계보는데 [7] 아스카영원히사랑해갤로그로 이동합니다. 08.15 117 0
2881544 실시간베스트 내 귀에 도청장치 사건 글 보니 생각나는 아까 쓴 글 발명도둑잡기갤로그로 이동합니다. 08.15 54 0
2881543 어떤 나라 사람들은 찻지피티라고 하네 발명도둑잡기갤로그로 이동합니다. 08.15 45 0
2881542 [플라이 미 투 더 문] 메인 예고편 발명도둑잡기갤로그로 이동합니다. 08.15 38 0
2881540 달착륙설 믿는 애들은 이건 어떻게 설명함? [7] 야옹아저씨갤로그로 이동합니다. 08.14 214 5
2881539 신입, 주니어 취업 질문 ㅇㅇ(180.69) 08.14 75 0
2881537 대기업들 미국으로 전부 이전하든 니들이 앰생인건 똑같잖아 ㅋㅋㅋ [1] 뒷통수한방(1.213) 08.14 52 0
2881530 내일부터 찬물샤워 미라클모닝 할거야 재현갤로그로 이동합니다. 08.14 28 0
2881528 나님 쉬야완⭐+ ♥냥덩이♥갤로그로 이동합니다. 08.14 58 0
2881523 크롬창 뒤로 보내니까 유튜브 렉걸리는데 ㅇㅇ(106.241) 08.14 49 0
2881521 수학 넘 잼씀 [1] ♥냥덩이♥갤로그로 이동합니다. 08.14 76 0
2881520 우연치 않게 엄청난 걸 발견해 버렸다... 프갤러(221.154) 08.14 78 0
2881517 8.14 국회 국제 심포지엄 생중계 / 전후 80년, 세계 그리고 한국 발명도둑잡기갤로그로 이동합니다. 08.14 39 0
2881513 모기 있는거 같당.. ♥냥덩이♥갤로그로 이동합니다. 08.14 59 0
2881507 퐁퐁남 석열이 도축 엔딩 뜨노 ㅠㅠ [1] 아스카영원히사랑해갤로그로 이동합니다. 08.14 96 0
2881503 이때 모모링은 귀여웠는데 ㅠ ♥냥덩이♥갤로그로 이동합니다. 08.14 69 0
2881502 도쿄 외곽 4인가족 집이 아스카영원히사랑해갤로그로 이동합니다. 08.14 57 0
2881500 나님 주무실게양⭐+ ♥냥덩이♥갤로그로 이동합니다. 08.14 57 0
2881499 데뷔 1년차 신입 걸그룹 스케줄 [1] 발명도둑잡기갤로그로 이동합니다. 08.14 52 0
2881498 결단력없이 떠내려온 결과가 지금입니다. 프갤러(220.84) 08.14 56 0
2881496 오 씨발 살려다오 [1] 골방외톨이갤로그로 이동합니다. 08.14 62 0
2881495 형들 파이썬 무료강의 둘중에 뭐가 더 좋아요? 프갤러(86.48) 08.14 40 0
2881494 요새 애니메이숀 색칠 쉬워졌겠지? 발명도둑잡기갤로그로 이동합니다. 08.14 35 0
2881493 MC Sniper / 인생 (Feat. 웅산) 발명도둑잡기갤로그로 이동합니다. 08.14 39 0
2881492 용산 갔다 왔다 외국인 사장님들 내 질문에도 답해주셔서 [6] 넥도리아(220.74) 08.14 56 0
2881491 영화 <살인자 리포트> 나왔대서 생각나는 예전 글 발명도둑잡기갤로그로 이동합니다. 08.14 54 0
2881490 한국 곳곳에서 숨 막히는 추격전이 시작된다! #버터플라이 발명도둑잡기갤로그로 이동합니다. 08.14 56 0
2881489 최종면접 봤는데 제발 붙었으면 좋겠다 [1] 프갤러(14.12) 08.14 79 0
2881488 광복절 알빠노 ㅇㅅㅇ 저녁은 초밥먹어야징 ㅇㅅㅇ 류류(118.235) 08.14 38 0
2881487 나님 낼 뛰뛰 해야징 같이 하실분 구함 [1] ♥냥덩이♥갤로그로 이동합니다. 08.14 54 0
2881486 프갤 좆같아서 슬슬 멀티함 [2] 아스카영원히사랑해갤로그로 이동합니다. 08.14 100 1
2881485 특이점 온다 노동해방시대 온다 ㅇㅇ [2] 뒷통수한방(1.213) 08.14 54 1
2881484 공부를 해도 또 까먹음 [4] 밀우갤로그로 이동합니다. 08.14 74 0
2881483 멍유는 내일도 출근해라 ㅇㅅㅇ [2] 류류(118.235) 08.14 56 0
2881482 사람은 변하지않음 뒷통수한방(1.213) 08.14 35 0
2881481 면접 존나 힘들다 ㅅㅂ;;; 프갤러(220.85) 08.14 47 0
2881480 조센징 개센징 씹센징 똥싼징 춍센징 손발이시립디다갤로그로 이동합니다. 08.14 39 0
2881479 조직스토킹으로부터 안전한나라를 만듭시다 [4] 손발이시립디다갤로그로 이동합니다. 08.14 56 0
2881478 패전기념일 연휴가 시작되었습니다 아스카영원히사랑해갤로그로 이동합니다. 08.14 47 0
2881477 바나나 ♥냥덩이♥갤로그로 이동합니다. 08.14 34 0
2881476 졸피뎀 ♥냥덩이♥갤로그로 이동합니다. 08.14 42 0
2881475 코딩 너무 어렵다 [1] 프갤러(119.194) 08.14 58 0
2881473 DI에 빠져부럿다 깃깃갤로그로 이동합니다. 08.14 62 0
2881472 나님 냥덩원 비밀요원.. [1] ♥냥덩이♥갤로그로 이동합니다. 08.14 61 0
2881471 패배자처럼 살기 싫으면 뭘 어떻게 해야하는걸까... [1] ㅇㅇ(223.39) 08.14 51 0
뉴스 아이브, ‘비밀 요원’으로 파격 변신…새 미니 앨범 ‘아이브 시크릿’ 기대 디시트렌드 08.16
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2