12 ms·
> the bitshift divide in particular comes from embedded and other speed concerns Please don't do this unless you are using a really bad toolchain: most compile
by saagarjha 7y ago
> the bitshift divide in particular comes from embedded and other speed concerns
Please don't do this unless you are using a really bad toolchain: most compilers will optimize x /= 2 for you.
- voltagex_ 7y agohttps://godbolt.org/z/nwk0Jm https://godbolt.org/z/nwk0Jm and https://godbolt.org/z/bGcD4Y https://godbolt.org/z/bGcD4Y show some differences - someone much better at assembly will have to explain this one.
- klipt 7y agohttps://www.geeksforgeeks.org/left-shift-right-shift-operators-c-cpp/ https://www.geeksforgeeks.org/left-shift-right-shift-operato... "The left shift and right shift operators should not be used for negative numbers. The result of is undefined behaviour if any of the operands is a negative number." Might be one reason?
- saagarjha 7y agoShifting by one and dividing by 2 aren't the same for signed integers, but the distinction goes away if you change the parameter to be unsigned: https://godbolt.org/z/GPJsdQ https://godbolt.org/z/GPJsdQ https://godbolt.org/z/m-rS90 https://godbolt.org/z/m-rS90
- nwallin 7y agoThe division case is optimized for size. The code for using a division instruction is smaller than the code for a shift followed by the magic to make it well behaved for negative integers. So it uses the division instruction. In general, always use -O2. -Os is only a good idea if you're on embedded and a -Os program fits in memory and -O2 doesn't. There really aren't any other cases where -Os is better.
- geoelectric 7y agoGood point! I think that's true of a lot of older "optimization" techniques--if they're that good, a compiler does them for you. I'm curious whether any compilers have specific rules to "re-optimize" obsolete practice. Like, assuming a platform does have a cheaper way to do /=2, do any compilers recognize that a >>1 in a given context is meant to be a div 2 and replace the code?