I need to repeatedly convert 1024+ consecutive 4 byte floats (range -1 to 1) to 2 byte shorts (range -32768 to 32767) and write to disk.
Currently I do this with a loop:
short v = 0;
for (unsigned int sample = 0; sample < length; sample++)
{
v = (short)(inbuffer[sample * 2] * 32767.0f);
fwrite(&v, 2, 1, file);
}
And this works, but the floating point calc and loop is expensive. Is there any way this could be optimized?
A typical Mac (objective-c tag, or are we talking about iphone here?) can do billions of float multiplications per second. fwrite however is a library call, which follows some indirections to write its data to some buffer and possibly flush it. It is better to fill your own buffer in a batch: