r/programming • u/mttd • Aug 11 '26
Moving integer division to floating-point is trivial
https://marc-b-reynolds.github.io/math/2026/08/10/IntDivByFP.html
112
Upvotes
r/programming • u/mttd • Aug 11 '26
View all comments
Show parent comment
30
u/tanner-gooding Aug 11 '26
TL;DR There's a reason compilers don't do this today and its probably never a real world win.
It's highly unlikely to be faster and there's a few reasons why.
There's then a few key points in division history:
Pre-2008
2008-2017 (Intel Nehalem and later)
2017
2018+
Where that gives two main pivot points to consider which influence the costs involved, first the size of the divisor (8, 16, 32, or 64-bits) and second the size of the dividend (8, 16, 32, 64, or 128 bits) -- i.e. you can do 8/8, 16/8, 16/16, 32/16, 32/32, 64/32, 64/64, and 128/64 operations.
So lets say you know for certain that you have a non-constant divisor (and therefore you can't switch over to shifts or multiplications instead) but that you do know that both the dividend and divisor fits into 24 or 53 bits. The best case scenarios are then essentially:
Pre-2008:
2008-2017
2017+
And noting that yes, some instructions get slower or have their lower bounds increase on newer. The hardware changes and you get more consistent results rather than ranges of best vs worst case. Its all tradeoffs and hardware as a whole gets faster, less latency, less stalls, etc.
The numbers above show that you're potentially saving a maximum of 65% time in "raw numbers" on the oldest hardware and wasting up to around 50% time on the latest hardware. However, there's a gotcha in that the ranges for integer division vary based on the number of bits in the dividend and since we know we're at most 24 (not 64) or 53 (not 128) bits, we're actually much closer to the lower ends of 32/32 and 64/64 (not the 64/32 and 128/64 worst cases).
So the savings are actually going to be much lower and potentially even a loss, particularly when you also factor in the crossing of integer to fp domains (a pipe stall, introducing hidden latency which is more accurately accounted for on later hardware), that you're unlikely to know the actual bounds of the inputs that well and so can't opt-in, that values outside 24/53 bits require more work for correct handling, etc
Its trivially a regression on the actual latest hardware and probably a regression even on much oldest hardware. We'll likely find even more ways to improve hardware in the future such that the gap closes even more.