Why is casting a double to an integer so slow?



I have a portion of a calculation which turns a triplet of double-precision coordinates (x,y,z), into an integer index. To do this, I am using an integer cast, of the form int cx = (int)(x/dx);. In testing, however, this seems much slower than I would expect; mere division is much faster.

Is there a reason why this operation takes so long? Is there a way of making it faster?


@jkingsley a couple of comments on the question

  1. can you change the title to read

    Why is casting a double to an integer so slow?

    its not clear why the the second occurrence of casting is needed in the question.

  2. unless I am missing something, in general to answer this it would be useful to know what language the code is written in and a little more about the code, the platform and the environment where this occurs as well as some actual comparative timing information - some general suggestions

    1. if this is a compiled language then providing a small workable fragment of code that exhibits the behavior as well as some pertinent timing information.

    2. for a compiled language it may be possible to also generate an assembly code listing of the executable code that goes with the example. The assembly code may well contain some clues.

    3. if this is an interpreted language then a working code fragment demonstrating the problem and the versions of the various tools and environments used would help someone looking to answer this


Hey @Chris and @jkingsley

I also plugged this in to google and found it has already been covered in some languages on stackoverflow and other venues, so moving it to “Out of Scope” until we refine it further.




@jma please read my meta discussion on out of scope. It might be useful to explore approaches that don’t simply eliminate things that are discussed elsewhere. Instead maybe linking to those and allowing for subsequent answers might be worth trying initially.

At the very least putting a link to a possible explanation seems a little more useful than deleting!

  1. Did you/someone else already change the title? Unless I’m being exceedingly blind, it looks like the title is currently “Why is casting a double to an integer so slow?”, which is the same thing you wrote? Otherwise, I can change it?

  2. I believe on the previous version of this, I tried to use the SO style of indicating language and environment via tags. If that’s now how this site intends to work, I’ll edit that in somewhere.