在C#中最快的方式从文件中读取的字节块,并转换为浮动[] [英] Fastest way in C# to read block of bytes from file and converting to float[]
问题描述
我需要转换/铸造编码2字节一短(INT16)值转换成浮点表示的字节数组,尽可能快的C#leanguage的快捷方式。性能瓶颈的方法是:
样本[示例] =(浮点)binraryReader.readInt16();
(IO巨大ammount的要求,所以我不得不转换成块读)
基本上我有一个包含声音块文件样品(〜100-600 MB)类型的短的话,我只能读数据块中设置的字节,我需要建立从每对字节的短,然后将其转换短期浮动表示,因为我需要存储的样本为。花车
我当前的代码看起来somtething像这样(在方法约2倍的性能提升上面,但还是长):
浮法[] =样品新的浮动[_samplesPerSplit]
字节[]数据=新的字节[_samplesPerSplit * 2];
的for(int c = 0;℃下numberOfChunks; C + = 1)
{
br.Read(数据,0,_samplesPerSplit * 2);
固定(字节* bytePtr =数据)
{
固定(浮动* floatPtr =采样)
{
字节*的RPO = bytePtr;
浮动* FPOS = floatPtr;
字节byte0的;
字节字节1;
短sampleShort;
为(INT样本= 0;样品LT; _samplesPerSplit;样品+ = 1)
{
字节1 = *(RPOS ++);
byte0的= *(RPOS ++);
//我occasionaly得到
//否定一个
的最小值//二进制补码数是无效的
//错误,如果我跳过此检查,但它会减慢
//整个过程更是
如果(byte0的== 128安培;&安培;字节1 == 0)
{
sampleShort = 32767;
}
,否则
{
sampleShort =(短)(((USHORT)(字节0))≤;< 8 |((USHORT)(字节1)));
}
*(FPOS ++)=(浮点)sampleShort;
}
}
}
ProcessChunk(样本);
}
你可以试试这个:
固定(字节* bytePtr =数据)
{
固定(浮动* floatPtr =样本)
{
短*的RPO =(短*)bytePtr;
浮动* FPOS = floatPtr;
为(INT样本= 0;样品LT; _samplesPerSplit;样品+ = 1)
{
* FPOS ++ =(浮点)(*的RPO ++);
}
}
}
I need a fast way in C# leanguage of converting/casting array of bytes encoding one short (int16) value for 2bytes into float representation, as fast as possible. Performance bottleneck was method:
samples[sample] = (float)binraryReader.readInt16();
(huge ammount of IO calls so i had to convert to block read)
Basically i have file containing block of sound samples (~100-600 mb) of type of short, then, as i can only block read set of bytes, i need to construct short from each pair of bytes and then convert that short to float representation as i need to store samples as floats.
my current code looks somtething like this (about 2x performance improvement over method above, but still to long) :
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);
}
you can try this:
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++);
}
}
}
这篇关于在C#中最快的方式从文件中读取的字节块,并转换为浮动[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!