簡體   English   中英

C#中最快的方法是從文件中讀取字節塊並轉換為float []

[英]Fastest way in C# to read block of bytes from file and converting to float[]

我需要在C#leanguage中快速轉換/轉換字節數組,將2字節的一個short(int16)值編碼為float表示,盡可能快。 性能瓶頸是方法:

samples[sample] = (float)binraryReader.readInt16();

(巨大的IO調用,所以我不得不轉換為塊讀取)

基本上我有包含聲音樣本塊(~100-600 mb)類型的短文件,然后,因為我只能阻止讀取字節集,我需要從每對字節構造短路然后將該短路轉換為浮點數表示我需要將樣本存儲為浮點數。

我目前的代碼看起來像這樣(比上面的方法提高了2倍的性能,但仍然很長):

    float[] samples = new float[_samplesPerSplit];
    byte[] data = new byte[_samplesPerSplit * 2];

    for (int c = 0; c < numberOfChunks; c += 1)
    {
        br.Read(data, 0, _samplesPerSplit * 2);

        fixed (byte* bytePtr = data)
        {
            fixed (float* floatPtr = samples)
            {
                byte* rPos = bytePtr;
                float* fPos = floatPtr;

                byte byte0;
                byte byte1;
                short sampleShort;

                for (int sample = 0; sample < _samplesPerSplit; sample += 1)
                {
                    byte1 = *(rPos++);
                    byte0 = *(rPos++);

                    // I occasionaly get 
                    //          "Negating  the minimum value of a 
                    //          twos complement number is invalid" 
                    // error if i skip this check, but it slows down 
                    // whole process even more
                    if (byte0 == 128 && byte1 == 0)
                    {
                        sampleShort = 32767;
                    }
                    else
                    {
                        sampleShort = (short)(((ushort)(byte0)) << 8 | ((ushort)(byte1)));
                    }

                    *(fPos++) = (float)sampleShort;
                }
            }
        }
        ProcessChunk(samples);
    }

你可以試試這個:

    fixed (byte* bytePtr = data)
    {
        fixed (float* floatPtr = samples)
        {
            short* rPos = (short*)bytePtr;
            float* fPos = floatPtr;

            for (int sample = 0; sample < _samplesPerSplit; sample += 1)
            {
                *fPos++ = (float)(*rPos++);
            }

        }
    }

您是否嘗試使用Bitwise操作

我不太了解他們,但是從Wiki和MY 以前的SO中我所了解到的內容:

按位運算通常比乘法和除法運算快得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM