Question says it all. Does anyone know if the following…
size_t div(size_t value) {
const size_t x = 64;
return value / x;
}
…is optimized into?
size_t div(size_t value) {
return value >> 6;
}
Do compilers do this? (My interest lies in GCC). Are there situations where it does and others where it doesn’t?
I would really like to know, because every time I write a division that could be optimized like this I spend some mental energy wondering about whether precious nothings of a second is wasted doing a division where a shift would suffice.
Even with
g++ -O0(yes,-O0!), this happens. Your function compiles down to:Note the
shrq $6, which is a right shift by 6 places.With
-O1, the unnecessary junk is removed:Results on g++ 4.3.3, x64.