A faster way to compute signed 64-bit floor division by constants
Ben Joffe’s post presents a faster way to compute signed 64-bit floor division[1] when the divisor is a constant known at compile time. Floor division rounds the result towards −∞, while standard (“truncated”) signed division rounds towards 0; the post quotes Hacker’s Delight: “floor division more often gives the result you want”. Benchmarks cover over 40 divisors with per-divisor throughput and latency results across many platforms, tested on ARM64 chips (MacBook Pro M4 Pro, Snapdragon X1-26-100) and x86 chips (AMD Ryzen 9 9950X3D, Intel Core i7); a snapshot for division by 86400 contrasts the performance of most languages’ built-in methods with the post’s fast alternatives. The technique works in all bit-widths and may suit some 32-bit or SIMD[2] code, but the biggest benefit is in 64-bit; it can also give a faster positive-modulus (remainder) and a faster “Euclidean” division, which differs from floor division for negative divisors.
The motivating example converts a Unix timestamp in seconds into a day count by dividing by 86400 (60×60×24), using a 64-bit timestamp because a 32-bit one holds only about ±68 years; standard truncated division returns incorrect results for most negative values, which matters for timestamps before 1970. At the machine level, compilers implement constant division as a multiplication by a magic multiplier[3] plus a shift, with a bump by 1 for negative inputs, and regular constant division usually costs around 1 multiplication plus 2–3 cycles. Constants that need extra corrections are called uncooperative divisors[4] by some authors; for division by 100 the multiplier needs all 64 bits, which makes it negative and leaves the result 2^64 too low until x is added to the upper register of the product.
The code is released under an MIT license; the fast function for division by 86400 computes m = M + (x >> 63), a sign-selected multiplier, and returns the 128-bit product x * m shifted right by 79 bits, accurate over the full signed 64-bit range. For testing, 65535 divisors from −32768 to 32767 are generated into a single self-contained C++ file that includes a boundary test, alongside a reusable C++ reference template with microarchitectural performance tweaks. The author notes the technique is simple enough that somebody has likely done it before, but found it documented nowhere.
Read the original benjoffe.comDiscussion
Discussion
The top comment praises the post and links a short note by Daan Leijen about the various forms of division, how they relate to each other, and which languages implement which.
Sources
-
benjoffe.com
A faster way to compute signed 64-bit floor division by constants


