디시인사이드 갤러리

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

갤러리 본문 영역

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

ㅆㅇㅆ(124.216) 2025.08.08 10:17:06
조회 105 추천 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/11/03 - -
AD 저녁 뭐먹지? 오늘의 메뉴 추천! 운영자 25/10/31 - -
2879709 나는 외주땜시 nest.js 공부중 [2] ㅆㅇㅆ찡갤로그로 이동합니다. 08.09 133 0
2879707 토스 코테 보통 어느정도 해야함? [3] 프갤러(211.234) 08.09 378 0
2879705 토스가 시험봄? [2] ㅆㅇㅆ찡갤로그로 이동합니다. 08.09 211 0
2879704 아오 토스 [2] 밀우갤로그로 이동합니다. 08.09 187 0
2879701 보통 회사에서 개발자 몇 년차부터 PL 맡김? [5] ㅇㅇ(118.235) 08.09 140 0
2879700 피아노도 취미로 괜찮은거같군요 현무E공인(58.225) 08.09 115 0
2879699 토스 next 시험봤는데 [4] 프갤러(110.13) 08.09 361 0
2879698 와..시간.. 프갤러(106.102) 08.09 148 0
2879696 나님 힐링즁⭐+ ♥냥덩이♥갤로그로 이동합니다. 08.09 97 0
2879690 <여행을 대신 해드립니다> 한대서 생각나는 예전 글 발명도둑잡기갤로그로 이동합니다. 08.09 120 0
2879688 속보지는 겉보지는 ♥냥덩이♥갤로그로 이동합니다. 08.09 124 0
2879685 <파인: 촌뜨기들> 예고편 발명도둑잡기갤로그로 이동합니다. 08.09 154 0
2879681 아버지 밑에서 일, 일주일 프갤러(121.172) 08.09 122 0
2879678 파인 임수점 발명도둑잡기갤로그로 이동합니다. 08.09 100 0
2879674 7 0 0 0 0원 받'으'세'요~~~ ㅇㅇ(106.101) 08.09 76 0
2879673 철이와 미애-너는 왜 발명도둑잡기갤로그로 이동합니다. 08.09 94 0
2879670 냥덩이 연예인 포르노 매매 이제는 안하지? 발명도둑잡기갤로그로 이동합니다. 08.09 109 0
2879669 내일배움카드가 발명도둑잡기갤로그로 이동합니다. 08.09 94 0
2879668 토스 코테 뭐냐 ㅇㅇ(218.155) 08.09 292 2
2879667 컨디션 조절이 가장 어려움 ♥냥덩이♥갤로그로 이동합니다. 08.09 99 0
2879665 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥냥덩이♥갤로그로 이동합니다. 08.09 97 0
2879642 박원-All of my life 발명도둑잡기갤로그로 이동합니다. 08.09 76 0
2879637 노션 띄어쓰기 어케함 [1] 프갤러(112.146) 08.09 132 0
2879628 내일배움카드로 개발자 부트캠에서 배우고싶은데 추천부탁드립니다 프갤러(61.254) 08.09 166 0
2879624 나님께 나쁜말 악플 ㄴㄴ ♥냥덩이♥갤로그로 이동합니다. 08.09 110 0
2879616 최.초.공.개 ♥냥덩이♥갤로그로 이동합니다. 08.09 101 0
2879615 함부로 다른 ip에 핑보내면 처벌받냐? [2] 프갤러(118.223) 08.09 162 0
2879612 토스 공채 이번에 역대급이긴 함 3만명 지원했음 [2] 프갤러(121.167) 08.09 344 0
2879611 ‘착한 사나이’ 문태유, 짧지만 강한 존재감! ‘신스틸러’ 활약 기대 발명도둑잡기갤로그로 이동합니다. 08.09 103 0
2879610 디씨 매물로 나왔데 프갤러(110.47) 08.09 100 0
2879609 나 중요부위 제모중인데 아이스팩으로 열식히면서 피부 염증 넥도리아(220.74) 08.09 114 0
2879608 해외주식이랑 선물, 옵션에 API가 유료라 ㅆㅇㅆ(124.216) 08.09 139 0
2879607 흠.. ♥냥덩이♥갤로그로 이동합니다. 08.09 92 0
2879606 해외주식, 해외선물 등등 이게 분야가 왜 세부적으로 다르지 ㅆㅇㅆ(124.216) 08.09 90 0
2879600 잼땅 ♥냥덩이♥갤로그로 이동합니다. 08.09 90 0
2879596 에구구.. ♥냥덩이♥갤로그로 이동합니다. 08.09 124 0
2879590 좆소ㄹㅈㄷ네 [4] 프갤러(175.223) 08.09 159 0
2879588 중요 부위 제모의 중요성 특유 냄새 제거 가능 넥도리아(220.74) 08.09 109 0
2879586 한국에서 살아가는법 프갤러(61.79) 08.09 94 0
2879572 말로는 프로그래밍 방법론 전문가 [2] ㅇㅇ(211.234) 08.09 151 5
2879569 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥냥덩이♥갤로그로 이동합니다. 08.09 91 0
2879564 엄마 초심 잃었는데 어떻게 된거냐 야발 ㅇㅅㅇ... [1] ㅇㅇ(223.39) 08.09 110 0
2879556 [속보]관세문제 해결 안됬다 한국경제 최악의 리스크 2찢명 ♥냥덩이♥갤로그로 이동합니다. 08.09 104 0
2879555 개발자는 디지털 사법고시다 프갤러(106.101) 08.09 138 0
2879553 시발 존나무서운 요즘 초딩 6학년 근황ㄷㄷ.jpg ㅇㅇ(113.192) 08.09 156 0
2879551 검은 잠자리..ㅇㅅㅇ 헤르 미온느갤로그로 이동합니다. 08.09 174 0
2879550 태연 ㅇㅅㅇ 헤르 미온느갤로그로 이동합니다. 08.09 89 1
2879549 하루 한 번 헤르미온느 찬양 헤르 미온느갤로그로 이동합니다. 08.09 112 0
2879541 깨어있는자는 나뿐인가.. 현무E공인(58.225) 08.09 119 0
2879536 오후9시취침 새벽4시기상 미라클모닝 시작 현무E공인(58.225) 08.09 115 0
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

디시미디어

디시이슈

1/2