디시인사이드 갤러리

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

갤러리 본문 영역

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

ㅆㅇㅆ(124.216) 2025.08.08 10:17:06
조회 62 추천 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 - -
공지 프로그래밍 갤러리 이용 안내 [92] 운영자 20.09.28 46337 65
2881773 양양 후기 ♥냥덩이♥갤로그로 이동합니다. 21:01 5 0
2881772 여름바다는 확실히 습하당 ♥냥덩이♥갤로그로 이동합니다. 21:00 3 0
2881771 도와주세용ㅠ 11갤로그로 이동합니다. 21:00 7 0
2881770 나님이 마시는 술⭐+ ♥냥덩이♥갤로그로 이동합니다. 20:46 5 0
2881769 유튜브 뮤직 알고리즘 너무 구리더라 [1] 헬마스터갤로그로 이동합니다. 20:37 9 0
2881768 썩은내 적은 쓰레기에서 극심한 쓰레기가 됩니다. 프갤러(220.84) 20:37 9 0
2881766 윤미향 비난의 상당수 원인은 성매수, 성추행에 대한 죄책감 때문이다 발명도둑잡기갤로그로 이동합니다. 20:30 9 0
2881765 신봉선과 냥덩이의 결혼을 허가합니다 [2] 발명도둑잡기갤로그로 이동합니다. 20:26 15 0
2881764 오늘의 소설 영화 실마리: FBI, CIA 등에 마약 수사로 포섭된 래퍼 발명도둑잡기갤로그로 이동합니다. 20:22 19 0
2881763 게임 개발 공부하려고 프리서버 뜯어보고 있는데 ㅇㅇ갤로그로 이동합니다. 20:14 11 0
2881762 AI 나오고 느끼는 것이 AI가 최고의 스승이다. [2] ㅆㅇㅆ(124.216) 20:10 28 0
2881761 전광훈 현상의 뿌리를 파헤치다 [기자의 추천 책] 발명도둑잡기갤로그로 이동합니다. 20:05 7 0
2881757 요즘 느끼는 것이 그냥 하면 해볼만하더라 [1] ㅆㅇㅆ찡갤로그로 이동합니다. 19:52 21 0
2881756 여름밤바다⭐+✨☀+⚡+☄++ ♥냥덩이♥갤로그로 이동합니다. 19:46 13 0
2881755 술먹고도 안피곤하단걸 자랑으로 생각하는 애들이 있네... ㅇㅇ(223.39) 19:45 11 0
2881753 ai 창작러로써 배운거... ㅇㅇ(106.102) 19:39 17 0
2881752 경상도 여자가 예쁨 [1] ♥냥덩이♥갤로그로 이동합니다. 19:37 18 0
2881750 어제 맥주 2리터먹고 오늘 하루종일 잠잤음 ㅇㅅㅇ;; ㅇㅇ(223.39) 19:35 13 0
2881749 뮤지컬 우키시마마루 봤다 발명도둑잡기갤로그로 이동합니다. 19:25 17 0
2881748 유다 배신 비슷한 설화가 근방 신화에 더 먼저 있었나 발명도둑잡기갤로그로 이동합니다. 19:12 8 0
2881747 개발자 면접 썰.txt [1] 프갤러(58.29) 19:12 49 0
2881746 바이브 코딩으로 프로그램 만드는대 프갤러(45.130) 19:09 20 0
2881745 노인을 혐오 비하하면 왜 안됨??노인새끼들이 먼저 2030 갈라치기선동하 뒷통수한방(1.213) 19:08 9 0
2881744 서현역 야부림도 벌써 2년이 지났네 ㅇㅅㅇ 류류(118.235) 19:02 14 0
2881738 You are being Watched.. [1] ♥냥덩이♥갤로그로 이동합니다. 18:42 27 0
2881736 최원종 같은 애들이 모인게 국짐당 개혁신당인데 ㅇㅅㅇ 류류(118.235) 18:41 16 0
2881733 좇센살이 ) 노력하면 평범하게 살수있음 뒷통수한방(1.213) 18:37 20 0
2881731 일본 이민을 꿈꾸던 [1] 발명도둑잡기갤로그로 이동합니다. 18:25 31 0
2881730 데이터베이스 솔루션 엔지니어 취업 어떰 [6] 프갤러(221.163) 18:21 38 0
2881729 [하얼빈] 메인 예고편 발명도둑잡기갤로그로 이동합니다. 18:15 13 0
2881727 하나의 명제로 모든걸 이해하려는 우둔함 [1] ♥냥덩이♥갤로그로 이동합니다. 18:03 24 0
2881725 일본 옛날 게시물 보면 부모 뽑기 게임이라는 말 보는데 [3] ㅆㅇㅆ(124.216) 17:38 40 0
2881723 금융권 IT 정년까지 일할수있음? [3] ㅇㅇ(106.101) 17:10 50 0
2881722 노력 루피 사진 원본 찾았다 발명도둑잡기갤로그로 이동합니다. 17:07 10 0
2881721 신경망 설계 책 읽고 있는중 [2] ㅆㅇㅆ(124.216) 17:03 44 0
2881720 2014년부터 쓸모가 없습니다. 프갤러(220.84) 16:59 15 0
2881719 의외로 건강에 안 좋은 스포츠 [2] 발명도둑잡기갤로그로 이동합니다. 16:49 31 0
2881718 저장용 [2] ♥냥덩이♥갤로그로 이동합니다. 16:38 32 0
2881716 5성급 호텔 불편한점 ♥냥덩이♥갤로그로 이동합니다. 16:29 26 0
2881715 오늘도 프붕이와 대한민국 아저씨들의 안전과 평화를 기원합니다. [3] 넥도리아(223.38) 16:02 21 0
2881714 미소녀랑 야스하는 중이니까 좀 닥쳐봐 ㅇㅅㅇ 류류(118.235) 16:00 23 1
2881713 류큐 류류 봇 확실 넥도리아(223.38) 15:59 15 0
2881712 존잘 류류의 멋진 인생⭐+ ♥냥덩이♥갤로그로 이동합니다. 15:56 28 0
2881711 지금도 잘생기긴했는데 존잘남의 인생은 어떤인생일까 류류(118.235) 15:53 16 1
2881710 나님이 좋아하는 회 종류 [1] ♥냥덩이♥갤로그로 이동합니다. 15:44 30 0
2881709 류류 니애미 윤미향 ㅅㄱ [1] ♥냥덩이♥갤로그로 이동합니다. 15:43 35 0
2881708 돈만 많으면 남자가 질퍼기 처럼 생겨도 결혼하는구나 류류(118.235) 15:41 21 1
2881707 나님 애널 저녁은 해산물❤+ 경포대 ㅌㅊ ♥냥덩이♥갤로그로 이동합니다. 15:40 17 0
2881706 다큐3일 안동역 엔딩 뭐노 [2] 아스카영원히사랑해갤로그로 이동합니다. 15:35 76 0
뉴스 배우 송강호, 갤럭시코퍼레이션과 전속계약 디시트렌드 08.14
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2