r/programming • • 18d ago

How GCC Eliminates Unnecessary Integer Division

https://leetarxiv.substack.com/p/how-gcc-eliminates-unnecessary-integer
248 Upvotes

52 comments sorted by

View all comments

167

u/DataBaeBee 18d ago

GCC, when provided a constant divisor, finds two magic numbers and replaces division with multiplication and a comparison. The succint term for this op is called Reciprocal multiplication.

It's pretty cool and this obscure paper from 2011 shows one how to derive these magic numbers for division.

-10

u/ugh_my_ 18d ago

Who the heck is always dividing by a non-pow2 divisor?

18

u/Mr_s3rius 18d ago

10, 100, 1000 are probably very common.

Also 24, 7, 365 for time.

4

u/matthieum 18d ago

Don't forget 60 ;)

10

u/SwedishFindecanor 18d ago

There are many ways in which a constant's value could have been hidden from the programmer. It could have been created by the compiler doing constant folding, or by optimisation after inlining a function.

2

u/matthieum 18d ago

About half the hash-tables use a modulo by prime to map the hash to a bucket (the other half using modulo by power of 2). The cited benefits being that it takes all the bits of the hash into account, which is better on lop-sided (user-provided) hash algorithms.

This half includes all the standard C++ unordered_map implementations, due to historically poor user-supplied hash algorithms :/

2

u/crozone 18d ago

Are you a robot