디시인사이드 갤러리

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

갤러리 본문 영역

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

ㅆㅇㅆ(124.216) 2025.08.08 10:17:06
조회 55 추천 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 - -
2880092 한국 기업 된 알리익스프레스코리아, 홈플러스 인수전 나설까 발명도둑잡기갤로그로 이동합니다. 08.10 269 0
2880091 결국 ai에게 오래 못가 다 대체될까 ㅇㅇ(211.211) 08.10 56 0
2880089 생수 스캔들, 프랑스를 뒤흔들다 발명도둑잡기갤로그로 이동합니다. 08.10 28 0
2880087 아 씨발 걍 도커 게속 쓸껄 왜 바꿨을까 ㅆㅇㅆ(124.216) 08.10 48 0
2880085 도커쓰다가 Rancher로 바꿨는데 컴포즈 빌드 자체가 안됨 ㅆㅇㅆ(124.216) 08.10 43 0
2880083 "조국 사면하면 유승준도 입국 허용해야" 李 대통령에 요청한 팬들 발명도둑잡기갤로그로 이동합니다. 08.10 58 0
2880082 클로드 쓰면서 코딩 더 많이 하게됨 [2] ㅆㅇㅆ찡갤로그로 이동합니다. 08.10 77 0
2880081 한국에서 펌웨어는 자동차말고는 직장이 없나요? [1] ㅇㅇ(118.235) 08.10 63 0
2880078 아 왜 아무것도 하기가 싫냐 [3] 루도그담당(58.239) 08.10 59 0
2880077 저도 먹고 살아야죠 ㅎㅎ 프갤러(61.79) 08.10 33 0
2880076 김대범 싸인회 [1] 발명도둑잡기갤로그로 이동합니다. 08.10 48 0
2880075 TEMPEST 맞는 듯. 내 OFFLINE 컴퓨터 도청방식. [4] 프갤러(182.227) 08.10 57 0
2880071 본인이 싫어하는 표현은 반려동물입니다 [6] 헬마스터갤로그로 이동합니다. 08.10 68 1
2880069 내가 좀 꼰대 같을지 모르겠지만 [8] 루도그담당(58.239) 08.10 95 0
2880067 진정한 개발자는 지피티 성능 박은거 정도로 당황하지 않음 [5] ㅇㅇ(121.186) 08.10 92 0
2880066 BHC뿌링클 언제먹어도맛있네 [8] 개멍청한유라갤로그로 이동합니다. 08.10 54 0
2880064 얀르쿤이 옳았다 [1] 초코냥갤로그로 이동합니다. 08.10 67 0
2880059 아니 근데 지피티 5가 그렇게 못써먹을정도인가? 걍 지침대로하면 [5] ㅆㅇㅆ(124.216) 08.10 112 0
2880058 기세닷! 기세로 밀러부쳐어어엇!! ♥냥덩이♥갤로그로 이동합니다. 08.10 42 0
2880057 GPT 5 진짜 못써먹겠는데... [5] 프갤러(1.224) 08.10 105 0
2880055 이번 대구 방화사건 보니까 느끼는건데 [4] ㅆㅇㅆ찡갤로그로 이동합니다. 08.10 105 0
2880049 보통 C# 서는 이벤트 사용을 권장하지만 내부적으로 델리게이트 쓰긴함 [2] ㅆㅇㅆ(124.216) 08.10 83 0
2880048 gpt5 너무 멍청하다 [1] 초코냥갤로그로 이동합니다. 08.10 77 0
2880044 뉴비 C# 질문 좀 할수있을까요.. [6] ㅇㅇ(162.210) 08.10 103 0
2880042 기쁨의 원천 ♥냥덩이♥갤로그로 이동합니다. 08.10 27 0
2880041 이번에 지피티5써보니까 더 좋아진거같은데 난 [4] ㅆㅇㅆ(124.216) 08.10 70 0
2880038 챗티씨5 기능이 퇴화했다고 하는구나 [3] 헬마스터갤로그로 이동합니다. 08.10 74 1
2880033 ms 2025년에도 xaml갖고 떡치는거 재밋지않냐? [6] 헬마스터갤로그로 이동합니다. 08.10 76 0
2880028 스프링 아예 안한지 1년 넘었는데 다시 도전해볼까 [5] ㅇㅇ(118.235) 08.10 89 0
2880025 레전드 도배 갤러리 프갤러(122.199) 08.10 54 0
2880024 냥덩이가 가장 좋아하는 계절❤+ ♥냥덩이♥갤로그로 이동합니다. 08.10 36 0
2880020 비추론 모델에 추론 prompt 썻더니 존나 똑똑해짐 프갤러(125.143) 08.10 52 0
2880019 이번에 NEST.JS 해보면서 느끼는건데 생각보다 어렵네 [1] ㅆㅇㅆ(124.216) 08.10 66 1
2880018 보물을 찾아 모험을 떠나구 싶구낭 ♥냥덩이♥갤로그로 이동합니다. 08.10 39 0
2880016 1루에 9줄 감사의 코딩 [6] 공기역학갤로그로 이동합니다. 08.10 91 0
2880009 흠.. 금월까진 모르겟구 담달초까진 가능할듯 ♥냥덩이♥갤로그로 이동합니다. 08.10 45 0
2880001 나님 왤케 특별하실깡..? ♥냥덩이♥갤로그로 이동합니다. 08.10 33 0
2879997 VS스튜디오 쓰다가 VS코드 쓰면 항상 느끼지만 [6] ㅆㅇㅆ(124.216) 08.10 98 0
2879996 롤토체스 시즌 15 공략 개추 프갤러(121.133) 08.10 43 0
2879990 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥냥덩이♥갤로그로 이동합니다. 08.10 31 0
2879988 너무 피곤하다 하 씨발 [1] ㅆㅇㅆ(124.216) 08.10 60 0
2879984 6년차연봉3500경력32살개발자일요일아침시작 현무E공인(58.225) 08.10 69 0
2879983 나님 뛰뛰하니깡 썩은몸이 다시 생명을 얻는둣? ♥냥덩이♥갤로그로 이동합니다. 08.10 44 0
2879976 인류 최초의 역사! 우리가 몰랐던 성경의 뿌리, 고대 신화의 비밀 발명도둑잡기갤로그로 이동합니다. 08.10 39 0
2879975 결국 제미니 2.5 프로 딥리서치로 Ada 책 작성한다. 나르시갤로그로 이동합니다. 08.10 38 0
2879974 물 ㅇㅅㅇ 헤르 미온느갤로그로 이동합니다. 08.10 33 0
2879973 태연 ㅇㅅㅇ [3] 헤르 미온느갤로그로 이동합니다. 08.10 59 0
2879972 하루 한 번 헤르미온느 찬양 헤르 미온느갤로그로 이동합니다. 08.10 35 0
2879971 극한 상황에서 체력, 여성이 남성보다 우수 [달콤한 사이언스] 발명도둑잡기갤로그로 이동합니다. 08.10 37 0
2879969 안녕히계세요 여러분-! 분해 넥도리아(220.74) 08.10 40 0
뉴스 정동원, 박진영과 ‘집대성’ 출연! “신곡 비하인드와 세대 공감 토크” 디시트렌드 08.11
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2