디시인사이드 갤러리

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

갤러리 본문 영역

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

ㅆㅇㅆ(124.216) 2025.08.08 10:17:06
조회 77 추천 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/09/01 - -
AD 가전디지털, 신학기 페스타! 운영자 25/08/29 - -
2883797 Sony 케이블 고장나서 DIY할 수 있을까... [3] 넥도리아(223.38) 08.23 90 0
2883796 취업하고 십따 무관갤로그로 이동합니다. 08.23 68 0
2883795 애니로 언제나오려낭.. ♥냥덩Art♥갤로그로 이동합니다. 08.23 58 0
2883794 시노자키 아이와 섹스 100회 vs 머기업 취업 [3] 아스카영원히사랑해갤로그로 이동합니다. 08.23 179 0
2883793 러스트는 패러다임이 문제인게 맞습니다 나르시갤로그로 이동합니다. 08.23 63 0
2883792 냥줍덩줍❤+ ♥냥덩Art♥갤로그로 이동합니다. 08.23 68 0
2883791 나 요즘 세부구현 점점 잊는데 이게 맞나싶다 ㅆㅇㅆ(124.216) 08.23 84 0
2883789 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥냥덩Art♥갤로그로 이동합니다. 08.23 54 0
2883788 프붕친구들 오늘도 로우레벨로 웹을 하는 간지나는 자신을 꿈꾸나 보구만 ㅇㅇ갤로그로 이동합니다. 08.23 74 0
2883787 모투 서비스 할라면 자문업 등록 해야함. [1] ㅆㅇㅆ(124.216) 08.23 78 0
2883786 모의투자서비스 만들어보고싶은데 쓸만한api가 없노 [2] 밀우갤로그로 이동합니다. 08.23 91 0
2883783 자바 씨샵 파이썬 다 내부적으로 c 돌리는거 맞음? [3] ㅇㅇ(110.10) 08.23 113 0
2883781 ghidra 간만에 만지는데 [2] ㅇ.ㅇ(59.151) 08.23 81 0
2883780 33살인데 이 스펙이면 관세사 도전 해볼까? [1] ㅇㅇ(118.235) 08.23 102 0
2883779 장원영 약간 부정적 인식이었는대 컨셉을 넘어서 태도가 된게 보이니 ♥냥덩Art♥갤로그로 이동합니다. 08.23 99 0
2883778 확실히 낮은 짧아지는게 보임 ♥냥덩Art♥갤로그로 이동합니다. 08.23 77 0
2883777 그대는 어떻게 살것인가 공기역학갤로그로 이동합니다. 08.23 73 0
2883776 날씨 거의씹 ♥냥덩Art♥갤로그로 이동합니다. 08.23 82 0
2883775 앎이란 마법을 현실의 원리로 끌어내리는 과정 ♥냥덩Art♥갤로그로 이동합니다. 08.23 64 0
2883773 전공만 뽑는다 ♥냥덩Art♥갤로그로 이동합니다. 08.23 93 0
2883772 다른 게임 안티치트 분석하는데 [4] 루도그담당(58.239) 08.23 99 0
2883771 오후우와 이야기의 핵심에 다가가는 해설 - 표지 변경! 프갤러(121.172) 08.23 57 0
2883770 UpWork쪽도 의뢰 들어왔는데 UpWork가 한국 사이트보다 안좋은듯 ㅆㅇㅆ(124.216) 08.23 77 0
2883769 오늘도 한 건 해결 [3] ㅆㅇㅆ(124.216) 08.23 95 0
2883768 1찍둥절~ ♥냥덩Art♥갤로그로 이동합니다. 08.23 60 0
2883767 인생 진로 조언좀 제발... [3] ㅇㅇ(118.235) 08.23 130 0
2883765 러스트는 어디서 뿅 하고 튀어나온게 아니라 그간의 교훈을 집대성한 언어 [4] 프갤러(221.146) 08.23 87 0
2883764 베네수엘라 앞바다 미군함 집결 뭐노? [1] 아스카영원히사랑해갤로그로 이동합니다. 08.23 113 0
2883762 나님 한 달 가계부 최초공개⭐+ ♥냥덩Art♥갤로그로 이동합니다. 08.23 73 0
2883759 러스트는 어려운게 문제가 아니라 패러다임이 나르시갤로그로 이동합니다. 08.23 72 0
2883758 안철수님은 러스트가 아닌 어셈블리를 했죠 나르시갤로그로 이동합니다. 08.23 82 0
2883756 너무 천박함- 프갤러(121.172) 08.23 98 1
2883754 동양은 서양을 못 이기는구낭 ♥냥덩Art♥갤로그로 이동합니다. 08.23 90 0
2883748 33살인데 스펙이 너무 짬뽕임? [2] ㅇㅇ(58.229) 08.23 117 0
2883747 인지과학조져라 손발이시립디다갤로그로 이동합니다. 08.23 67 0
2883746 쬬은주말(՞•⌄•՞)✧ 스텔쬬아갤로그로 이동합니다. 08.23 72 0
2883743 아아.. 루프인강.. 언제 어디서 어떤 형식으로던.. ♥냥덩Art♥갤로그로 이동합니다. 08.23 65 0
2883742 배경지식이란게 참 중요하지요 ♥냥덩Art♥갤로그로 이동합니다. 08.23 84 0
2883741 [애니뉴스] 오후우를 좋아할 수밖에 없는 이유- 프갤러(121.172) 08.23 62 0
2883740 나님 균형감각 뛰어낭 ♥냥덩Art♥갤로그로 이동합니다. 08.23 69 0
2883739 퇴사 후 이직준비중인데 ㅇㅇ(118.235) 08.23 97 0
2883738 무역+영어 시너지있는 4차산업 기술 추천좀.. ㅇㅇ(58.229) 08.23 67 0
2883737 러스트 전혀 어렵지 않다. 전정프를 러스트로 바꾸면 국비도 할 수 있음 프갤러(110.8) 08.23 131 1
2883734 러스트 특 ) 자기가 정상인인줄암 인류 0.0001%속하면서 ㅋㅋㅋ 뒷통수한방(1.213) 08.23 85 1
2883733 좆벌레인생 학벌세탁할 대학원 + 자격증 추천좀 [7] ㅇㅇ(118.235) 08.23 135 0
2883732 러스트해서 대박부자되고 성공한사람 프갤러(1.213) 08.23 90 0
2883731 cpp 이용자가 cpp 욕하는데 발끈 안하는건 cpp에 진짜로 문제가 [1] 프갤러(110.8) 08.23 117 0
2883730 마이클잭슨-거울 속의 사람 발명도둑잡기갤로그로 이동합니다. 08.23 77 0
2883729 러스트는 18위 하위권 언어입니다 나르시갤로그로 이동합니다. 08.23 89 0
2883728 연봉 수억받는 과기부장관도 러스트 문법 모르는거같은데 프갤러(1.213) 08.23 87 0
뉴스 시슬리 앰버서더 이주빈, 가을 스타일링 화보 공개 디시트렌드 10:00
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2