Re:Converting binary floating-point numbers to integers
by pm215 on Saturday October 23, 2021 @06:11AM
(#28967100)
Hmm? The A64 instruction set includes instructions to convert from floating point to integer and set the Inexact FPCR flag if the conversion isn't exact, which is pretty much exactly the operation we want here (it's one of the various FCVT insns). The catch is that Inexact is a sticky flag, so you'd need to clear it first. That might work out slower than "convert float to int, then int to float and see if you got back the same value" as the first C++ function does. It's also going to be awkward for a compiler to do so you'd be dropping down to inline asm. Would be interesting to benchmark, though.
(Edit: and as one of the blog post comments notes, for the special case of double to 32 bit integer the FCVTJS insn does this and puts the 'exact or not' information conveniently in the Z flag to branch on.)
The results aren't too surprising. The ARM, which is a RISC, doesn't show much difference because it doesn't have much in the way of good complex instructions suited to the task, and in this case you can actually beat the compiler by optimising at the source level. x86 is still fundamentally CISC in nature and making use of the complex instructions is better especially when they are optimised in hardware. I don't have those machines nor environment to compare, but if you look at the code size, you might find the compiler has generated very similar code for the long and short version on ARM, whereas it certainly won't be smart enough to "recompress" your long version back into CISC instructions.