Home

Awesome

fastdiv

GoDoc

Fast division, modulus and divisibility checks for divisors known only at runtime via the method of:

"Faster Remainder by Direct Computation: Applications to Compilers and Software Libraries" Daniel Lemire, Owen Kaser, Nathan Kurz arXiv:1902.01961

Usage:

var divisor uint32 = 3

// intialize a divisor at runtime
d := fastdiv.NewUint32(divisor)

// use it repeatedly
var total uint32
for i := uint32(1); i < 10; i++ {
	total += d.Div(i)
	if d.Divisible(i) {
		fmt.Printf("%d is divisible by %d\n", i, divisor)
	}
}
fmt.Printf("Sum of quotients = %d", total)

// Output:
// 3 is divisible by 3
// 6 is divisible by 3
// 9 is divisible by 3
// Sum of quotients = 12

The method works by pre-computing an approximate inverse of the divisor such that the quotient is given by the high part of the multiplication and the remainder can be calculated by multiplying the fraction contained in the low part by the original divisor. In general, the required accuracy for the approximate inverse is twice the width of the original divisor. For divisors that are half the width of a register or less, this means that the quotient can be calculated with one high-multiplication (top word of a full-width multiplication), the remainder can be calculated with one low-multiplication followed by a high-multiplication and both can be calculated with one full-width multiplication and one high-multiplication.

On amd64 architecture for divisors that are 32-bits or less, this method can be faster than the traditional Granlund-Montgomery-Warren approach used to optimize constant divisions in the compiler. The requirement that the approximate inverse be twice the divisor width means that extended arithmetic is required for 64-bit divisors. The extended arithmetic makes this method is somewhat slower than the Granlund-Montgomery-Warren approach for these larger divisors, but still faster than 64-bit division instructions.

The per operation speed up over a division instruction is ~2-3x and the overhead of pre-computing the inverse can be amortized after 1-6 repeated divisions with the same divisor.

opsizevarconstfastdivvar / fastdiv# to breakeven
divuint1615.5 ns5.46 ns5.32 ns2.9x1
moduint1616.2 ns7.68 ns7.68 ns2.1x1
divint1616.7 ns5.91 ns6.55 ns2.5x1
modint1617.5 ns8.86 ns8.86 ns2.0x1
divuint3215.5 ns7.28 ns5.53 ns2.8x2
moduint3215.7 ns9.63 ns7.09 ns2.2x2
divint3216.0 ns5.91 ns5.91 ns2.7x2
modint3216.1 ns8.86 ns8.27 ns1.9x2
divuint6421.4 ns5.91 ns6.89 ns3.1x5
moduint6420.3 ns8.30 ns8.87 ns2.3x6
divint6426.2 ns7.26 ns8.51 ns3.0x5
modint6425.8 ns9.57 ns16.8 ns1.5x6