Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do modern compilers optimize the x * 2 operation to x << 1?

Does the C++ compiler optimize the multiply by two operation x*2 to a bitshift operation x<<1?

I would love to believe that yes.

like image 712
Maxime Rouiller Avatar asked Oct 24 '08 20:10

Maxime Rouiller


People also ask

How do compilers optimize?

Compiler optimization is generally implemented using a sequence of optimizing transformations, algorithms which take a program and transform it to produce a semantically equivalent output program that uses fewer resources or executes faster.

Do compilers Optimise code?

Compilers are free to optimize code so long as they can guarantee the semantics of the code are not changed.

How does the C++ compiler optimize?

The C/C++ compiler compiles each source file separately and produces the corresponding object file. This means the compiler can only apply optimizations on a single source file rather than on the whole program. However, some important optimizations can be performed only by looking at the whole program.

Why do compilers perform optimization in code?

Optimization of the code is often performed at the end of the development stage since it reduces readability and adds code that is used to increase the performance.


1 Answers

Actually VS2008 optimizes this to x+x:

01391000  push        ecx       int x = 0;      scanf("%d", &x); 01391001  lea         eax,[esp]  01391004  push        eax   01391005  push        offset string "%d" (13920F4h)  0139100A  mov         dword ptr [esp+8],0  01391012  call        dword ptr [__imp__scanf (13920A4h)]       int y = x * 2; 01391018  mov         ecx,dword ptr [esp+8]  0139101C  lea         edx,[ecx+ecx]  

In an x64 build it is even more explicit and uses:

    int y = x * 2; 000000013FB9101E  mov         edx,dword ptr [x]       printf("%d", y); 000000013FB91022  lea         rcx,[string "%d" (13FB921B0h)]  000000013FB91029  add         edx,edx  

This is will the optimization settings on 'Maximize speed' (/O2)

like image 178
Rob Walker Avatar answered Oct 09 '22 00:10

Rob Walker