Unity 3D : 多線程將 byte [] 陣列 轉成 int [] 陣列

前言 :

高速將 byte[] 轉 int [],主要是讀取大檔案,一些函式需要用 int[] 處理,那這時就可以用上。

啥? 哪個函式需要 int[] 這麼古怪的方式處理? Unity ComputeShader …

要用 GPU 處理檔案解碼,那就要轉成 int [] 陣列了….

你們可以比較單線程與多線程的速度差異,多線程大約快 2 倍以上。

我寫成一個函數,你們直接拿來用就可以。

先來看程式碼吧。

C # :

int[] ByteArray_To_IntArray(byte[] b)
    {
        int[] i = new int[b.Length];

        System.Diagnostics.Stopwatch time = new System.Diagnostics.Stopwatch();
        time.Start();

        int thread_count = 8; // 設定線程數量

        // 如果設定的線程數量可以被整除,那就用多線程,否則用單線程。
        if (i.Length % thread_count != 0)
        {
            //單線程
            for (int x = 0; x < b.Length; x++)
            {
                i[x] = b[x];
            }
        }
        else
        {
            //多線程
            int thread_size = i.Length / thread_count;

            using (ManualResetEvent finish = new ManualResetEvent(false))
            {
                int currentThreadCount = thread_count;

                for (int t = 0; t < thread_count; t++)
                {
                    int start = thread_size * t;
                    int end = thread_size * t + thread_size;
                    int[] v = new int[] { start, end };

                    ThreadPool.QueueUserWorkItem((System.Object state) =>
                    {
                        int[] v2 = state as int[];
                        int start2 = v2[0];
                        int end2 = v2[1];

                        for (int x = start2; x < end2; x++)
                        {
                            i[x] = b[x];
                        }

                        if (Interlocked.Decrement(ref currentThreadCount) == 0)
                        {
                            finish.Set();
                        }
                    }, v);
                }
                // 等待所有 Thread 執行完畢
                finish.WaitOne();
            }
        }

        time.Stop();
        print("轉型花費: " + time.Elapsed.TotalSeconds + " 秒");

        return i;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值