Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiency of C vs Assembler

How much faster is the following assembler code:

shl ax, 1

Versus the following C code:

num = num * 2;

How can I even find out?

like image 482
Kyle Rosendo Avatar asked Nov 27 '22 21:11

Kyle Rosendo


1 Answers

Your assembly variant might be faster, might be slower. What made you think that it is necessarily faster?

On the x86 platform, there are quite a few ways to multiply something by 2. I would expect a compiler to do add ax, ax, which is intuitively more efficient than your shl because it doesn't involve a potentially stored constant ('1' in your case).

Also, for quite a long time, on a x86 platform the preferred way of multiplying things by constants was not a shift, but rather a lea operation (when possible). In the above example that would be lea eax, [eax*2]. (Multiplication by 3 would be done through lea eax, [eax*2+eax])

The belief in shift operations being somehow "faster" is a nice old story for newbies, which has virtually no relevance today. And, as usual, most of the time your compiler (if it is up-to-date) has much better knowledge about the underlying hardware platform than people with naive love for shift operations.

like image 142
AnT Avatar answered Dec 21 '22 06:12

AnT