4 ms·
> int bar(int num) { return num / 2; } > > Doesn't get optimized to a single shift right, because the that won't work if num is negative. Nit: some might
by SkiFire13 11mo ago
> int bar(int num) { return num / 2; }
>
> Doesn't get optimized to a single shift right, because the that won't work if num is negative.
Nit: some might think the reason this doesn't work is because the shift would "move" the sign bit, but actually arithmetic shifting instructions exist for this exact purpose. The reason they are not enough is because shifting provides the wrong kind of division rounding for negative numbers. This can however be fixed up by adding 1 if the number is negative (this can be done with an additional logical shift for moving the sign bit to the rightmost position and an addition).
- kragen 11mo agoWill shift, shift, and add be slower or faster than a divide instruction on machines with a divide instruction?
- SkiFire13 11mo agoMost likely no, division instructins generally take as much as 10-20 other arithmetic/logic instruction.
- abainbridge 11mo agoGood point. I guess there are more cases than just this one where I'd like to be able to tell the compiler I don't care about rounding behaviour and would prefer the fastest code. Like -ffast-math but for integer operations. I don't think that exists. I wonder why.