Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is faster: x<<1 or x<<10?

I don't want to optimize anything, I swear, I just want to ask this question out of curiosity. I know that on most hardware there's an assembly command of bit-shift (e.g. shl, shr), which is a single command. But does it matter (nanosecond-wise, or CPU-tact-wise) how many bits you shift. In other words, is either of the following faster on any CPU?

x << 1; 

and

x << 10; 

And please don't hate me for this question. :)

like image 422
Armen Tsirunyan Avatar asked Nov 20 '10 17:11

Armen Tsirunyan


People also ask

Is bit shifting faster?

Bit-shifting is still faster, but for non-power-of-two mul/div by the time you do all your shifts and add the results it's slower again.

What does the << do in C?

The << operator shifts the left-hand value left by the (right-hand value) bits. Your example does nothing! 1 shifted 0 bits to the left is still 1. However, 1 << 1 is 2, 1 << 2 is 4, etc.


1 Answers

Potentially depends on the CPU.

However, all modern CPUs (x86, ARM) use a "barrel shifter" -- a hardware module specifically designed to perform arbitrary shifts in constant time.

So the bottom line is... no. No difference.

like image 131
nimrodm Avatar answered Sep 18 '22 18:09

nimrodm