r/programming • u/benjoffe • Oct 28 '26
A faster way to compute signed 64-bit floor division by constants
https://www.benjoffe.com/fast-floordiv
200
Upvotes
r/programming • u/benjoffe • Oct 28 '26
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.
2
u/Bisqwit Oct 28 '26
Does this new algorithm also produce modulo efficiently?
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.