Our server application does a lot of integer tests in a hot code path, currently we use the following function:
inline int IsInteger(double n)
{
return n-floor(n) < 1e-8
}
This function is very hot in our workload, so I want it to be as fast as possible. I also want to eliminate the “floor” library call if I can. Any suggestions?
A while back I ran a bunch of timings on the most efficient way to convert between floats and integers, and wrote them up. I also timed techniques for rounding.
The short story for you is: converting from a float to an int, or using union hacks, is unlikely to be an improvement due to a CPU hazard called a load-hit-store — unless the floats are coming from RAM and not a register.
Because it is an intrinsic, abs(floor(x)-eps) is probably the fastest solution. But because this is all very sensitive to the particular architecture of your CPU — depending on very sensitive things like pipeline depth and store forwarding — you’ll need to time a variety of solutions to find one that is really optimal.