디시인사이드 갤러리

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

갤러리 본문 영역

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

ㅆㅇㅆ(124.216) 2025.08.08 10:17:06
조회 95 추천 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/10/13 - -
AD iPad Pro 사전예약!! 운영자 25/10/17 - -
2879343 재테크강좌 Show me the money-> the liberty 발명도둑잡기갤로그로 이동합니다. 08.08 75 0
2879340 구글 수수료 정책 진짜 개좆같네 ㄹㅇ [1] 뉴진파갤로그로 이동합니다. 08.08 102 0
2879339 전세계 냥덩이들이여 일제히 봉기하라❤+ ♥냥덩이♥갤로그로 이동합니다. 08.08 53 0
2879338 장난쳤다가 일 존나 커짐 ㅋㅋㅋㅋㅋㅋ ㅇㅇ(211.234) 08.08 93 3
2879335 4 + 1 컴퓨존 주문했습니다. 입금도 했습니다. 점심시간에 죄송합니다 도리스아(220.74) 08.08 101 0
2879334 스톨만의 프로그래밍 언어 호불호 언급 발명도둑잡기갤로그로 이동합니다. 08.08 95 0
2879333 안철수도 러스트 프로그래밍한다고함 ㅋ 뒷통수한방(1.213) 08.08 119 0
2879332 한미일영 코메디의 가장 큰 문제는 아무리 적나라하게 웃기고 풍자를 해도 발명도둑잡기갤로그로 이동합니다. 08.08 85 0
2879331 앱개발 하려는데 뭐 만들지 추천좀 [1] (118.235) 08.08 108 0
2879330 점점 러스트 못하면 도태되는 세상이 되어가는 중 ㄷㄷㄷㄷ [1] 프갤러(218.154) 08.08 133 0
2879328 아 회사컴 씨발 [2] 루도그담당(118.235) 08.08 124 1
2879327 자바쓰는이유는 딱 1가지 밖에없지 [5] 프갤러(121.174) 08.08 247 1
2879326 삭제했는데, 프리랜서라서 좆같다... [4] ㅆㅇㅆ(124.216) 08.08 157 0
2879323 봤을테니 삭제해둠. 대부분 내 코드지만 내 코드가 아니라서 [2] ㅆㅇㅆ(124.216) 08.08 137 0
2879322 ❤+❤+❤+ [2] 어린이노무현갤로그로 이동합니다. 08.08 92 0
2879320 흠.. 확실히 꿀잠잔날은 뭔가 땡기는게 없군 ♥냥덩이♥갤로그로 이동합니다. 08.08 77 0
2879318 김성태 "전한길·전광훈·신천지·통일교 모인 당 돼 버려…위헌정당 빌미" 발명도둑잡기갤로그로 이동합니다. 08.08 81 1
2879317 갑질좌파 강선우와 좌청래의 관계 ♥냥덩이♥갤로그로 이동합니다. 08.08 63 0
2879316 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥냥덩이♥갤로그로 이동합니다. 08.08 76 0
2879315 꿀잠잔 나님의 두뇌는 지구생명체 1황이당 By 나님 [1] ♥냥덩이♥갤로그로 이동합니다. 08.08 83 0
2879314 근데 좀 궁금한게 분명히 GPT도 깃 최상급 프로그래머들 코드 다넣었을 [6] ㅆㅇㅆ(124.216) 08.08 160 0
2879312 모바일기기는 무조건 가벼워야 ♥냥덩이♥갤로그로 이동합니다. 08.08 67 0
2879311 근데 진짜 깃 최상급 코드들 보면 경이롭지 않냐? 지피티한테 뽑아달라해도 [4] ㅆㅇㅆ(124.216) 08.08 151 0
2879309 예전에도 말했지만 자바 개발자 연봉은 기술보단 범죄행위에서 비롯됩니다. 프갤러(218.154) 08.08 177 0
2879308 요새 내 코드 스타일 변화는 명세 짜두고 제네릭으로 패턴 연결해둠 ㅆㅇㅆ(124.216) 08.08 114 0
2879307 코드는 일단 짜놓고 [2] 루도그담당(211.184) 08.08 112 0
2879306 12시쯤 나가볼까요... 도리스아(220.74) 08.08 98 0
2879304 지피티 5는 제미나이보다는 우위, OPUS 4.1보다는 낮은 그런 느낌듯 ㅆㅇㅆ(124.216) 08.08 106 0
2879303 연쇄살인 조직폭력 관련자 220.84가 오늘 꼭 해야 할 일 발명도둑잡기갤로그로 이동합니다. 08.08 128 0
2879302 컴퓨터네트워크 선수과목 있음? 프갤러(118.217) 08.08 92 0
2879301 기초생활수급자 인생. 근데 솔직히 절반만 주셔도 되는데, 데이터복구에 도리스아(220.74) 08.08 98 0
2879300 좌폐아는 4050 아니더라도 모자른 잉여들밖에 없넹 [1] ♥냥덩이♥갤로그로 이동합니다. 08.08 85 0
2879299 뭔 자뻑이여 인간 코드보다 못하다는건데 ㅆㅇㅆ(124.216) 08.08 73 0
2879298 빈부격차 심한 사회에서 적은 사회보다 인기 많은 노래 특징 발명도둑잡기갤로그로 이동합니다. 08.08 91 0
2879295 118.235 발명도둑잡기갤로그로 이동합니다. 08.08 91 0
2879294 지피티 류 코드의 문제점이 메모리를 한번에 올려 자꾸 ㅆㅇㅆ(124.216) 08.08 87 0
2879293 휴대용 레트로 콘솔 게임기 KNULLI 운영체제 부팅 스크린 발명도둑잡기갤로그로 이동합니다. 08.08 82 0
2879292 지피티 5 코드 전반적으로 맥락에 따른 코드 변화를 미묘하게 못잡아낸다. ㅆㅇㅆ(124.216) 08.08 80 0
2879291 왜 펌웨어랑 윈도우는 커서같은 툴이안나오는것임? 네오커헠(211.234) 08.08 111 0
2879290 지피티 5 써보는데 여전히 소스제네레이터보다 리플랙션쓰네 [1] ㅆㅇㅆ(124.216) 08.08 114 0
지피티 5로 코드 뱉어봤는데 여전히 좀 아쉽 ㅆㅇㅆ(124.216) 08.08 95 0
2879288 용산을 일주일에 1번은 기본으로 가네요. 도리스아(220.74) 08.08 96 0
2879287 왜 윾과장은 메시지를 쳐안읽는 걸까요? [1] 아스카영원히사랑해갤로그로 이동합니다. 08.08 92 0
2879285 자바는 뭔가 일하고있다는 표시를 내는 언어임 [2] ㅇㅇ갤로그로 이동합니다. 08.08 120 0
2879283 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥냥덩이♥갤로그로 이동합니다. 08.08 78 0
2879282 GPT-5가 좋은 게 뭐냐면 [1] 에이도비갤로그로 이동합니다. 08.08 137 0
2879281 gpt5.0 써봉사람들 평이 먼가 그저그런데? [2] 밀우갤로그로 이동합니다. 08.08 157 0
2879280 5가 여태 나온 모델 짬뽕해서 넣은건가 [3] 루도그담당(211.184) 08.08 108 0
2879278 지피티는 코드성능 별론거같은데 [4] ㅆㅇㅆ(124.216) 08.08 115 0
2879276 뭐냐 5 나왔네 루도그담당(211.184) 08.08 99 0
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

디시미디어

디시이슈

1/2