Which of the following techniques is the best option for dividing an integer by 2 and why?
Technique 1:
x = x >> 1;
Technique
Make your intentions clearer...for example, if you want to divide, use x / 2, and let the compiler optimize it to shift operator (or anything else).
Today's processors won't let these optimizations have any impact on the performance of your programs.
The answer to this will depend on the environment you're working under.
x /= 2
into x >>= 1
, the presence of a division symbol will raise more eyebrows in that environment than using a shift to effect a division.x >>= 1
with a comment explaining its reasoning is probably best just for clarity of purpose.x /= 2
. Better to save the next programmer who happens to look at your code the 10 second double-take on your shift operation than to needlessly prove you knew the shift was more efficient sans compiler optimization.All these assume unsigned integers. The simple shift is probably not what you want for signed. Also, DanielH brings up a good point about using x *= 0.5
for certain languages like ActionScript.
I am telling for the purpose of programming competitions. Generally they have very large inputs where division by 2 takes place many times and its known that input is positive or negative.
x>>1 will be better than x/2. I checked on ideone.com by running a program where more than 10^10 division by 2 operations took place. x/2 took nearly 5.5s whereas x>>1 took nearly 2.6s for same program.
Just use divide (/
), presuming it is clearer. The compiler will optimize accordingly.
Use the operation that best describes what you are trying to do.
Note that they are not exactly equivalent. They can give different results for negative integers. For example:
-5 / 2 = -2
-5 >> 1 = -3
(ideone)
x / 2
is clearer, and x >> 1
is not much faster (according to a micro-benchmark, about 30% faster for a Java JVM). As others have noted, for negative numbers the rounding is slightly different, so you have to consider this when you want to process negative numbers. Some compilers may automatically convert x / 2
to x >> 1
if they know the number can not be negative (even thought I could not verify this).
Even x / 2
may not use the (slow) division CPU instruction, because some shortcuts are possible, but it is still slower than x >> 1
.
(This is a C / C++ question, other programming languages have more operators. For Java there is also the unsigned right shift, x >>> 1
, which is again different. It allows to correctly calculate the mean (average) value of two values, so that (a + b) >>> 1
will return the mean value even for very large values of a
and b
. This is required for example for binary search if the array indices can get very large. There was a bug in many versions of binary search, because they used (a + b) / 2
to calculate the average. This doesn't work correctly. The correct solution is to use (a + b) >>> 1
instead.)