将范围-1的浮点数转换为1的快速方法是短的?

Mor*_*ess 3 c audio objective-c audio-recording

我需要重复将1024+连续4字节浮点数(范围-1到1)转换为2字节短路(范围-32768到32767)并写入磁盘.

目前我通过循环执行此操作:

short v = 0;
for (unsigned int sample = 0; sample < length; sample++) 
{
    v = (short)(inbuffer[sample * 2] * 32767.0f);
    fwrite(&v, 2, 1, file);
}
Run Code Online (Sandbox Code Playgroud)

这是有效的,但浮点计算和循环是昂贵的.有什么办法可以优化吗?

Nor*_*ame 6

short v = 0;
for (unsigned int sample = 0; sample < length; sample++) 
{
    v = (short)(inbuffer[sample * 2] * 32767.0f);
    // The problem is not here-------^^^^^^^^^^^
    fwrite(&v, 2, 1, file);        
    // it is here ^^^^^^^
}
Run Code Online (Sandbox Code Playgroud)

一个典型的Mac(objective-c标签,或者我们在这里谈论iphone?)每秒可以进行数十亿次浮点乘法.然而,fwrite是一个库调用,它跟随一些间接,将其数据写入某个缓冲区并可能刷新它.最好在批处理中填充自己的缓冲区:

short v[SZ] = 0;
// make sure SZ is always > length, or allocate a working buffer on the heap.
for (unsigned int sample = 0; sample < length; sample++) 
{
    v[sample] = (short)(inbuffer[sample * 2] * 32767.0f);
}
fwrite(v,sizeof(v),1,file);
Run Code Online (Sandbox Code Playgroud)