디시인사이드 갤러리

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

갤러리 본문 영역

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

ㅆㅇㅆ(124.216) 2025.08.08 10:17:06
조회 29 추천 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/04 - -
AD 가전디지털, 휴대폰 액세서리 SALE 운영자 25/08/08 - -
공지 프로그래밍 갤러리 이용 안내 [92] 운영자 20.09.28 46161 65
2879488 “팔레스타인에 따뜻한 한 끼를” 손흥민, 후원 호소 발명도둑잡기갤로그로 이동합니다. 01:07 0 0
2879487 LLM은 제미니가 갑이다 나르시갤로그로 이동합니다. 00:55 4 0
2879486 호날두는 왜 유니폼 교환을 거부했을까? 발명도둑잡기갤로그로 이동합니다. 00:52 4 0
2879485 vscode 치명적 버그 있음 나르시갤로그로 이동합니다. 00:50 11 0
2879484 메시를 주목하는 이유, "선수 이전에 사람"이니까 발명도둑잡기갤로그로 이동합니다. 00:42 6 0
2879483 vscode 기반 에디터들의 고질적인 문제 프갤러(218.159) 00:37 32 1
2879482 진짜 디자이너 잘 만나는 것도 복임 [1] 에이도비갤로그로 이동합니다. 00:03 29 0
2879481 "세계 불륜 1위국은 태국, 절반이 경험"…그럴 만한 이유 있다 발명도둑잡기갤로그로 이동합니다. 08.08 12 0
2879480 윤석열 마누라 이번엔 밀수 의혹 야옹아저씨갤로그로 이동합니다. 08.08 13 0
2879479 네이버·인텔·KAIST 'AI칩 동맹' 좌초 발명도둑잡기갤로그로 이동합니다. 08.08 12 0
2879477 사냥 나섰다 사냥당해… 美 백만장자, 버팔로에 들이받혀 즉사 발명도둑잡기갤로그로 이동합니다. 08.08 8 0
2879476 웨미 프로그래머스 코테 왜 언어닥스빠짐? [1] 프갤러(221.150) 08.08 24 0
2879475 1시간 남았어요~~~막~~~챠!! ㅇㅇ(106.101) 08.08 20 0
2879474 포트폴리오 사이트 만들려고 웹 디자인 커미션 맡겼는데 [5] ㅇㅇ갤로그로 이동합니다. 08.08 41 0
2879473 하루종일 주술회전봄 뒷통수한방(1.213) 08.08 15 0
2879472 나님 조만간 인간이 우주문명이 될 가능성 칼럼 [1] ♥냥덩이♥갤로그로 이동합니다. 08.08 21 0
2879471 립부 탄 인텔 CEO, 트럼프 사퇴 압박에 “잘못된 정보 유포” 반박 발명도둑잡기갤로그로 이동합니다. 08.08 13 0
2879470 못생긴애가 좋아한다고 티내면 좃같은게 [4] ♥냥덩이♥갤로그로 이동합니다. 08.08 32 0
2879469 스프링이 보이다 안 보이다 그러네..., 힘들다... 도리스아(220.74) 08.08 12 0
2879468 창문 열어놓고 맥주 마시면서 영화 ㄱㅆㅅㅌㅊ !! ♥냥덩이♥갤로그로 이동합니다. 08.08 14 0
2879467 홈서버에 gpt-oss (20b) 세팅해야게따.. 어린이노무현갤로그로 이동합니다. 08.08 28 0
2879466 서비스센터직원이 부품 빼가는거 가능하냐? 도리스아(220.74) 08.08 11 0
2879465 못볼꼴을 보아버리고야 만것입니다. 프갤러(220.84) 08.08 15 0
2879464 진정한 프로는 나사 방향 몇시에 고정되어있는지 알아야 하지 않을가 도리스아(220.74) 08.08 11 0
2879462 gpt5.0나오기전에 혁신인듯 입엄청털어서 [2] 밀우갤로그로 이동합니다. 08.08 36 0
2879461 걍 전문대 성인반안가고 고졸로 살까ㅠ ㅇㅇ(14.52) 08.08 13 0
2879460 정말 어처구니가 없지 예수님을 닮은 목사님 동지 두분은 발명도둑잡기갤로그로 이동합니다. 08.08 13 0
2879459 모르는게 약입니다. 모르는게 약이에요. 프갤러(220.84) 08.08 12 0
2879458 냥덩이인줄 알았는데 연금술사?⭐+ ♥냥덩이♥갤로그로 이동합니다. 08.08 13 0
2879457 GPT 모델 왜 통합됐냐 [1] 프갤러(121.140) 08.08 40 0
2879456 "예약은 일사천리, 취소는 복잡" 제주 렌터카 '다크패턴의 덫' 발명도둑잡기갤로그로 이동합니다. 08.08 14 0
2879455 마귀새끼가 누굴 가르치겠다고 거길 갔을까요. 프갤러(220.84) 08.08 18 0
2879454 잇힝~ ♥냥덩이♥갤로그로 이동합니다. 08.08 19 0
2879453 좆같다. 벽느낀다 시발... 나는 왜 이 모양인가... ㅇㅇ(223.39) 08.08 24 0
2879452 극우 내란당 연설회 발명도둑잡기갤로그로 이동합니다. 08.08 11 0
2879450 개운하다 루도그담당(58.239) 08.08 14 0
2879449 간단한 ppt 작업 해줄사람... [1] 재현갤로그로 이동합니다. 08.08 28 0
2879448 국내 최대 커뮤니티 디시인사이드 매물로… 최대주주 유식대장 아니었네 발명도둑잡기갤로그로 이동합니다. 08.08 17 0
2879447 나님 집주소 최초 공개⭐ 현피 뜰 녀석들은 와라 ♥냥덩이♥갤로그로 이동합니다. 08.08 20 0
2879446 Odd 기술 공유 [1] 넥도리아(220.74) 08.08 42 0
2879445 오명을 뒤집어쓰는건 제가 해야했던 것인데요. 프갤러(220.84) 08.08 16 0
2879444 한국애들 존나 불쌍한거 106.101 씀 발명도둑잡기갤로그로 이동합니다. 08.08 31 0
2879443 저장용 ♥냥덩이♥갤로그로 이동합니다. 08.08 23 0
2879442 뭔가 연락하는사람 하나도없으니까 프리한데, 현무E공인(58.225) 08.08 29 0
2879441 ㅋㅅㅋ ♥냥덩이♥갤로그로 이동합니다. 08.08 14 0
2879440 오늘 내일 레딧에 글 쓰러 갈거다 ㅋㅋ 나르시갤로그로 이동합니다. 08.08 17 0
2879439 나님은 오탁이 아님 ♥냥덩이♥갤로그로 이동합니다. 08.08 19 0
2879438 나는조현병이야 나는내향적이야 손발이시립디다갤로그로 이동합니다. 08.08 19 0
2879437 자기와 의견이 다른 사람들 욕하지 않고는 정치글 못씀? ㅇㅅㅇ 헤르 미온느갤로그로 이동합니다. 08.08 15 0
뉴스 '비 마이 보이즈' 워너원 라운드 결과는? 세 번째 'TOP PICK' 관심 집중 디시트렌드 08.08
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2