Alex Rivera | Logout

How to speed up floating-point to integer number conversion?

Asked 2009-01-09T20:38:19.527
19

We're doing a great deal of floating-point to integer number conversions in our project. Basically, something like this

for(int i = 0; i < HUGE_NUMBER; i++)
     int_array[i] = float_array[i];

The default C function which performs the conversion turns out to be quite time consuming.

Is there any work around (maybe a hand tuned function) which can speed up the process a little bit? We don't care much about a precision.

Edit
Report

2 Answers

16

Most of the other answers here just try to eliminate loop overhead.

Only deft_code's answer gets to the heart of what is likely the real problem -- that converting floating point to integers is shockingly expensive on an x86 processor. deft_code's solution is correct, though he gives no citation or explanation.

Here is the source of the trick, with some explanation and also versions specific to whether you want to round up, down, or toward zero: Know your FPU

Sorry to provide a link, but really anything written here, short of reproducing that excellent article, is not going to make things clear.

answered 2009-01-10T06:26:53.393
0

rounding only excellent trick, only the use 6755399441055743.5 (0.5 less) to do rounding won't work.

6755399441055744 = 2^52 + 2^51 overflowing decimals off the end of the mantissa leaving the integer that you want in bits 51 - 0 of the fpu register.

In IEEE 754
6755399441055744.0 =

sign exponent mantissa
0 10000110011 1000000000000000000000000000000000000000000000000000

6755399441055743.5 will also however compile to 0100001100111000000000000000000000000000000000000000000000000000

the 0.5 overflows off the end (rounding up) which is why this works in the first place.

to do truncation you would have to add 0.5 to your double then do this the guard digits should take care of rounding to the correct result done this way. also watch out for 64 bit gcc linux where long rather annoyingly means a 64 bit integer.

answered 2011-10-11T15:57:02.967

Your Answer