r/programming • • Oct 28 '26

A faster way to compute signed 64-bit floor division by constants

https://www.benjoffe.com/fast-floordiv
200 Upvotes

13 comments sorted by

42

u/FickleQuail8944 Oct 28 '26

I don't think the first part of the article helps in really understanding what is going on. You need examples or visualizations. But just repeating the code is pointless.

28

u/benjoffe Oct 28 '26

Thanks. I've been working with low level code for quite some time now and I forgot how my brain used to work. Now that it's pointed out, I can see those examples would be quite opaque when coming at it fresh. I will consider adding a few tips.

For readers here: the multiplications and right shifts are a way of dividing without using hardware division (which is slow). A classic trick.

It can be understood with a decimal analagy. Imagine you can multiply huge numbers fast but are terribly slow at simple division. If you wanted to divide by 3, you could instead multiply by 333334, and then chop off the last 6 digits of your answer.

This works because 1/3 ~= 333334/1000000.

The code examples at the start are the same, but using binary. Right shifts chop off the rightmost binary digits.

The multipler is found by dividing a big number 2N by the divisor at compile time and rounding up. The shift amount is then "N".

-6

u/TlalocII Oct 28 '26

Why not teach llvm how to do this automatically?

18

u/matthieum Oct 28 '26

GCC & LLVM regularly optimize division by a constant, just check it on the compiler explorer.

Their implementations, however, may not be quite state of the art. Especially if using older versions.

State of the art code should, reasonably, produce state of the art assembly regardless of whether the compiler would on its own... which is a blessing and a curse of course: it's helpful with older compilers, but you may be missing out if a newer compiler comes with an even better version.


Knowing the techniques can still pay off, though, if you seek to implement it with run-time divisors.

2

u/R1chterScale Oct 29 '26

Knowing the techniques can still pay off, though, if you seek to implement it with run-time divisors.

Something that immediately pops to mind is libdivide

9

u/moschles Oct 28 '26

I'm not sure we are reading the same article? The one I see is long and has interactive diagrams. Perhaps the best technical blog I've ever seen.

2

u/Bisqwit Oct 28 '26

Does this new algorithm also produce modulo efficiently?

1

u/benjoffe Oct 29 '26

Hi, yes it does.
See the section "Fast Floor-Modulus and Euclidean Division".
If you don't require full 64-bit range, a faster option exists: search online for Lemire's "Faster Remainder by Direct Computation".

24

u/Successful-Money4995 Oct 28 '26

Looks good! Can I make a recommendation?

For every place that a variable can be constexpr, use constexpr. For example, all those variables M. It won't make a difference in the generated code but for the reader, it makes it obvious that a value is being computed at compile time.

9

u/Skaarj Oct 28 '26 edited Oct 28 '26

These are the articles that give me impostor syndrome for 2 weeks.

Great work.

2

u/limitless_grow 28d ago edited 27d ago

That's quite interesting for compilers.

However, because the samples use the seconds per day I had a look at my own gmtime_r wrapper (limitless_times) that requires about 6 integer divisions.

On a Raspberry Pi 5 my implementation takes about 17ns per call while the glibc requires 99ns. (It takes half of that time on my Ryzen but PCs are more hard to compare).

My logger uses a localtime_r wrapper which calls new_gmtime_r. For a logger speed is very important. Writing a logline into a memory buffer takes about 0.1 µs on the Ryzen and 0.3 µs on the Raspberry Pi 5.

Of course a localtime_r call is required once the second changes and for this one time every second only. If I replace all divisions in my gmtime_r wrapper and it becomes 4 times faster than I would save 12ns every second and my logger would be 0.0000012% faster.

I doubt that many people care much about the speed of time functions or the implementations of the compilers wouldn't be that slow.

My project includes a little benchmark of the time functions and the project has no dependencies. You can check it out and start run_tests.sh for building and running the tests. There are also Visual Studio projects. ( Don't cancel a test run in Windows because the test changes the timezone temporarily and you may have to reset it in the Windows time settings afterwards. )

-2

u/moschles Oct 28 '26

the headline looks boring af. But the actual article is a rollercoaster ride.