float -> int speed

Started by
7 comments, last by Humbaba 20 years, 5 months ago
how fast are float to int conversions? (relative to, say, a floating point multiply operation) For example, you want to take your float vector position and index into an array defining your environment so you do the (int) convertion on your float vector elements. I''ve heard it''s generally advisable to avoid type conversions because they''re slow. Is this true? -Stphen
Advertisement
Kind of slow. 6 cycles on a Pentium, according to this. But if you gotta do it, you gotta do it. So do it, and worry about it later if it turns out not to be fast enough.

"Sneftel is correct, if rather vulgar." --Flarelocke
that''s if you use FIST.
Most compilers are ansi compliant and fiddle with the FPU rounding modes, which takes considerably longer.
er, rounding? on a float->int conversion? uehm, no.

C and C++ at least just lop off any decimals, even in they''re 5.9999999 its still 5 as an int.
Yes, a standard C float->int conversion demonstrates one of many of a floating-point processor''s so-called rounding modes. So, sjelkjd is exactly correct.
quote:
er, rounding? on a float->int conversion? uehm, no.

C and C++ at least just lop off any decimals, even in they''re 5.9999999 its still 5 as an int.

Yes, and in order to do that it needs to fiddle with the rounding mode, and restore it after the truncation.
Because float to int conversion is nontrivial, there is also the function call overhead (at least in VC++ 6.0 and .NET, not sure how others do it)

I keep my objects'' screen positions in floating point, then when I plot them I have to use integers for the pixel position. Like this:

// object positions
float x=...
float y=...

// now put on screen
int xdest=(int)x;
int ydest=(int)y;

Unless I do everything in fixed-point math I can''t think of another way to do it. Is the way I''m doing it bad ?
Well, simply use your own function to do the conversion rather than using the runtime''s casting facilities. There are plenty of examples of fast float-to-int conversions out there, so just do a little Googling.

Truthfully, you probably don''t need to worry about this at what I assume is your current stage in development.
sorry c-junkie, but sjelkjd is correct.


Currently each time you call a cast to int, it first sets the rounding mode, and then casts it. Then it returns the rounding mode back again.
Also, it is all done in double precision.


If you want speed, use assembly to call things like fist. Also setting to single precision will give you about 4 times the speed. You HAVE to know what you want your rounding to behave as though.
Beer - the love catalystgood ol' homepage

This topic is closed to new replies.

Advertisement