To narrow down my question, let me describe my assumption and the experiment that I did...
My assumption: A code written in assembly language will run much faster than its C/C++ counterpart and also the executable size to be much smaller than that generated from C/C++ code.
The experiment: I wrote the below program in to bin2dec.c
#include <stdio.h>
int main()
{
long int binary, decimal, reminder, exp;
int i, j;
for(i=0; i<10000; i++)
{
for(j=0; j<1000; j++)
{
binary = 11000101;
exp = 1;
decimal = 0;
while(binary != 0)
{
reminder = binary % 10;
binary = binary / 10;
decimal = decimal + reminder * exp;
exp *= 2;
}
}
}
return 0;
}
Then generated the ASM code for it gcc -S bin2dec.c -o bin2dec.s
After that I compiled both the files as below
gcc bin2dec.c -o bin2dec_c
gcc bin2dec.s -o bin2dec_s
Test 1: Found out some internal details of both the files
[guest@localhost ASM]$ size bin2dec_c bin2dec_s
text data bss dec hex filename
951 252 4 1207 4b7 bin2dec_c
951 252 4 1207 4b7 bin2dec_s
Result: Both are exactly same...
Test 2: Executed the files and calculated the time taken
[guest@localhost ASM]$ time ./bin2dec_c
real 0m1.724s
user 0m1.675s
sys 0m0.002s
[guest@localhost ASM]$ time ./bin2dec_s
real 0m1.721s
user 0m1.676s
sys 0m0.001s
Result: Both are same. Some time the executable generated from ASM ran slower :-(
So the question is, whether my assumptions were wrong? If not, what mistake I did so that both the executables bin2dec_c and bin2dec_s ran at the same speed? Is there any better way to get ASM code from a C/C++ program or I should rewrite all the logic from the scratch in ASM to gain the advantage of speed and program size?
See Question&Answers more detail:os