Archived

This topic is now archived and is closed to further replies.

MattS423

Float to int is just slow...

Recommended Posts

Lots of compilers toggle the FPU rounding mode before doing the conversion, and that''s slow. Most compilers have an option to control that behaviour, but this might also break some code.

If a specific rounding mode is not really an issue, but you don''t want to interfere with the compiler, then the best thing is to use an ASM inline function to do the explicit conversion. Something like:

_asm {
fld dword ptr [float_value]
fistp dword ptr [int_value]
}

You can''t really go any faster than that, at least with a single isolated conversion (ie. if you''re writing more complex FPU code, pairing and overlapping can be used to speed it up even further).

Share this post


Link to post
Share on other sites
Yup, just to expand on what Yann said:

Every time you do a float to int cast, the compiler generates code which saves, changes and later restores the rounding mode (i.e. whether to round up, round down, truncate etc). This is required for ANSI compliance (the rounding mode in the ANSI standard is different to the one the x86 FPU is in on a PC).

You can use the fistp directly as posted by Yann or under MSVC set the /QIfist compiler option (not sure if it''s actually documented) which will do the same. Beware of course that both those methods with generate code which isn''t ANSI compliant. Usually that''s not a problem - the only time it might be is if your code needs to share data with other platforms (e.g. a networking app running on a Mac and a PC, both might perform exactly the same calculation but would have slightly different results if they were using different rounding modes).

If you look in the Intel Architecture Optimizations Guide (you can download it from developer.intel.com), there''s some code in there which performs ANSI compliant float to int which is faster than the standard _ftol CRT version the compiler uses.

--
Simon O''Connor
Creative Asylum Ltd
www.creative-asylum.com

Share this post


Link to post
Share on other sites
If you want quick conversion without rounding up then just convert the float to string, say called str, and use:

int a = (int)str[0]-49;

I''m not sure its 49, its the ANSCII start value of 0, if you want the actual number just write (int)"0" to somewhere.

Share this post


Link to post
Share on other sites
quote:
Original post by malpass
If you want quick conversion without rounding up then just convert the float to string, say called str, and use:

int a = (int)str[0]-49;

I'm not sure its 49, its the ANSCII start value of 0, if you want the actual number just write (int)"0" to somewhere.

float to string is gonig to be at least 1000 times slower than float to int.

and that would be (int)'0', but this whole (very wierd) thing wouldn't work.

[edited by - billybob on May 4, 2003 6:53:50 AM]

Share this post


Link to post
Share on other sites