Skip to content
Tech News
← Back to articles

Moving integer division to floating-point is trivial

read original more articles
Why This Matters

This article highlights that converting integer division and remainder operations to floating-point calculations can significantly improve performance due to shorter latency and higher throughput. Although it involves some complexity, the approach is straightforward and can be beneficial for hardware optimization, especially in scenarios where division operations are a bottleneck. This insight could influence future hardware design and software optimization strategies in the tech industry.

Key Takeaways

Integer division q=(x/y) and remainder (of Euclidean division) r=(x%y) hardware operations are very sad on current hardware. Typically very long latency and poor throughput. In contrast floating-point division is pretty happy: shorter latency, higher throughput and often more execution units to perform the operation. So there are cases it could be interesting to move some integer div/mod operations to floating point. But it’s PITA right? Actually I think it’s easy. The math is pretty straightforward so if I’ve made a mistake I expect to find out rather soon.

My claim is: for two integers x & y (signed or unsigned) that fit in 53/24 bits for double/single precision respectively, with both promoted to floating point then:

// floating-point: // d is the same integer as integer divide x / y // m is the same integer as integer remainder x % y // (in standard rounding mode: round-to-nearest, ties to even) d = trunc ( x / y ); // floor works for unsigned m = - fma ( d , y , - x ); // fma required // NOTE: if only want 'd' and it's being converted to an // integer then the truncate or floor operation is // free in the float to integer conversion.

in standard rounding mode.

From here on I will only consider unsigned integers since it’s the harder case (signed have a smaller max magnitude) but recall that floating point effective stores a signed magnitude quantity.

Some practical points:

this works by setting rounding-mode to TOWARD_ZERO and then back once done but hitting control words is often very expensive

and then back once done but hitting control words is often very expensive some hardware have division opcodes that allow choosing the rounding mode on some operations like division. Example AVX-512 has instrinsic: _mm_div_round_sd with example listed latency of 14 cycles.

... continue reading