디시인사이드 갤러리

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

갤러리 본문 영역

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

ㅆㅇㅆ(124.216) 2025.08.08 10:17:06
조회 74 추천 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/25 - -
이슈 느린 여행으로 삶의 속도를 찾는 유튜버 꾸준 운영자 25/08/26 - -
AD MD's pick 상반기 인기 노트북 운영자 25/08/26 - -
2884714 국힘 좆병신 같은 새끼 뽑혔네 [4] 아스카영원히사랑해갤로그로 이동합니다. 08.26 128 0
2884711 되다만 똥같은 것들이 남 긁는걸 가지고 스스로 우월하다고 정신승리함. 프갤러(218.154) 08.26 47 0
2884710 확실히 한국애들이 잘 긁히는경향이 있음 ㅇㅇ(58.229) 08.26 55 0
2884705 러스트를 볼때마다 종이 빨대가 생각남 ㅇ.ㅇ(59.151) 08.26 59 0
2884703 1인 개발보다 그냥 사람모아서 창업하는게 나을텐데 [7] 네오커헠(121.157) 08.26 194 0
2884692 업워크 며칠째 일을 못받네 ㅆㅇㅆ(124.216) 08.26 53 0
2884690 개고기 팔이는 그냥 저능한 일베충 빠돌이 상대로 있어보이는 척 프갤러(211.234) 08.26 49 0
2884684 인지과학조져라 손발이시립디다갤로그로 이동합니다. 08.26 62 0
2884670 영업중인가.? ㅇㅅㅇ 헤르 미온느갤로그로 이동합니다. 08.26 31 0
2884668 태연 ㅇㅅㅇ 헤르 미온느갤로그로 이동합니다. 08.26 35 0
2884666 하루 한 번 헤르미온느 찬양 헤르 미온느갤로그로 이동합니다. 08.26 62 0
2884605 누가 더 유명함 홀란드 제나 오르테가 디바(59.28) 08.26 85 0
2884599 단독보도) 러스트 언어를 배우면 안되는 결정적 이유 나르시갤로그로 이동합니다. 08.26 64 0
2884597 러빨러들이 허구한 날 타 언어를 쓰레기라 나르시갤로그로 이동합니다. 08.26 56 0
2884594 러스트, 반짝이는 갑옷의 무게 나르시갤로그로 이동합니다. 08.26 45 0
2884589 러빨러가 c/c++, 자바, 파이선 등의 언어 까듯, 러스트 까줄게요 나르시갤로그로 이동합니다. 08.26 46 0
2884580 러스트는 절름발이 쓰레기 언어입니다 나르시갤로그로 이동합니다. 08.26 46 0
2884572 서양존예 동양존예 차이 ㅇㅇ(58.229) 08.26 58 0
2884565 바텐더 내가 모든걸 다 잊을수있게 [2] 개멍청한유라갤로그로 이동합니다. 08.26 76 0
2884564 사실 러스트는 자바보다 후달려요 ㅎㅎ3 나르시갤로그로 이동합니다. 08.26 43 0
2884560 사실 러스트는 자바보다도 후달려요 ㅎㅎ 2 나르시갤로그로 이동합니다. 08.26 57 0
2884559 자바충일 될빠에 파이썬충이 될거임 뒷통수한방(1.213) 08.26 43 0
2884555 좇센 연봉 억단위인 과기부장관부터가 자바충인데 뒷통수한방(1.213) 08.26 51 0
2884552 좇센은 자바공화국 자격증공화국임 뒷통수한방(1.213) 08.26 36 0
2884550 준석이는 코딩할때마다 뽀록나서 요즘은 그냥 AI 잘 다룬다는 티내나본데 ㅆㅇㅆ(124.216) 08.26 63 0
2884542 사실 러스트는 자바보다도 후달려요 ㅎㅎ 나르시갤로그로 이동합니다. 08.26 38 0
2884527 준석이는 나랏세금으로 나랏일할시간이 개발함??? 뒷통수한방(1.213) 08.26 48 0
2884526 준석이는 왜 컴공으로 개발자 않하고 정치질하냐?? [1] 뒷통수한방(1.213) 08.26 106 0
2884524 준석이가 만든 프로그램인데 어캐생각함???? [9] ㅇㅇ(211.241) 08.26 148 0
2884523 코스플레이어가되… 꼬치의달인갤로그로 이동합니다. 08.26 47 0
2884501 나 안경낀게나음 안낀게나음? [2] ㅇㅇ(222.108) 08.25 119 0
2884500 시 독자 장점 발명도둑잡기갤로그로 이동합니다. 08.25 37 0
2884494 원정경기장에 사진 찍고 박수 받으러 가는게 아니다 발명도둑잡기갤로그로 이동합니다. 08.25 34 0
2884491 홈페이지 서버비용과 광고노출 수익 비교 프갤러(58.29) 08.25 45 0
2884490 러스트는 현대적인 틀딱 언어입니다. 나르시갤로그로 이동합니다. 08.25 48 0
2884489 인터넷 안되서 누웠다 발명도둑잡기갤로그로 이동합니다. 08.25 70 0
2884482 두달 넘게 케데헌 열풍, 뉴욕타임스 "미국 부모는 12번 아이들은 30번 발명도둑잡기갤로그로 이동합니다. 08.25 36 0
2884474 10분 전부터 내 방 노트북 크롬웹브라우저가 갑자기 또 느려졌다 발명도둑잡기갤로그로 이동합니다. 08.25 43 0
2884473 배달원이 발견한 베개에 피로 쓰인 숫자들… 그 의미는? 발명도둑잡기갤로그로 이동합니다. 08.25 43 0
2884469 윤석열의 심리 분석, 권위주의적 성격자 MBC 발명도둑잡기갤로그로 이동합니다. 08.25 54 0
2884467 "트럼프가 도울 것" 윤 어게인, 매번 기대했지만… 발명도둑잡기갤로그로 이동합니다. 08.25 55 0
2884462 nimf 출시가 2015년, 2016년인데 무슨 ㅎㅎ 나르시갤로그로 이동합니다. 08.25 40 0
2884460 이재명 선거운동중 발언했던 엔비디아 국부펀드 유사 트럼프 인텔 지분 발명도둑잡기갤로그로 이동합니다. 08.25 42 0
2884458 꿈을 위해 달려가는 모든분들에게 ㅇㅇ(58.229) 08.25 39 0
2884457 뉴프로 재앙지원금 500포인트 지원안내 헬마스터갤로그로 이동합니다. 08.25 48 0
2884456 의장대 도열 없으니 푸대접?…李 대통령 방미 오해와 진실 발명도둑잡기갤로그로 이동합니다. 08.25 59 0
2884450 맨날 정치글 도배하시는 분께서 친히 언급해주시니 감격스럽네요. 프갤러(110.8) 08.25 46 0
2884448 호동씨가 건강이 매우 안 좋기 때문에 발명도둑잡기갤로그로 이동합니다. 08.25 61 0
2884447 요즘 코딩 존나 현타오지않냐 [1] 프갤러(175.193) 08.25 82 0
2884446 님프 목적은 아무래도 러스트로 분탕쳐서 인지도 쌓은 뒤 프갤러(110.8) 08.25 34 0
뉴스 “아들 숙제 내지 마세요” 사유리, “뻔뻔해 보여” 5개월만에 입 열었다 디시트렌드 10:00
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2