Recently been optimising code in C, and been looking specifically at integer and floating point operation speed.
I wrote some code to run a for loop 1e9 times and time basic operations.
Obviously there is some overhead for the increments which is a small constant.
The results are pretty random.
The first table is VS08 release mode,optimised for speed, and no debug, on my AMD64 Athlon Newcastle 3200+ 2.21Ghz.
| I+ |
3.068 |
| I- |
3.92 |
| I* |
3.891 |
| I/ |
2.977 |
|
|
| D+ |
2.922 |
| D- |
4.118 |
| D* |
3.97 |
| D/ |
4.084 |
The second table is default no optimisation gcc, compiled using the default install of Dev-C++.
| I+ |
8.259 |
| I- |
8.021 |
| I* |
8.246 |
| I/ |
31.874 |
|
|
| D+ |
5.464 |
| D- |
7.817 |
| D* |
8.762 |
| D/ |
10.448 |


The main thing to note is that different compilers have different speeds for running operations such as +,-,*,/. The second is that it is hard to get reliable timings for the operations in C due to the floating point accuracy and other runtime programs using cpu time.
Interestingly double addition is faster than integer addition. IN * and -, double is slightly slower in VS, and slower for gcc in *, but slightly faster in -. Double division is slower than integer division in VS, but much faster in gcc. I don’t understand why gcc is so slow at integer division. Maybe it did not optimise for it.
Below is the self contained code I used. It is not pretty code but it is simple to understand and it works.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
float timer(int T){
static double then=0.0;
static double clocks=0;
double now,diff;
now=(double)clock()/((double)(CLOCKS_PER_SEC));
diff=now-then;
if (T <= 0) then=now;
return((float)diff);
}
int main(void){
int i,i1,i2,i3;
double timetaken,d1,d2,d3;
i1=4;
i2=2;
d1=3.141592653589793238;
d2=4.626433832795028841;
timetaken=timer(0);
for (i=1;i<=1e9;i++){i3=i1+i2;}
timetaken=timer(1);
printf(“I+ %f\n”,timetaken);
timetaken=timer(0);
for (i=1;i<=1e9;i++){i3=i1-i2;}
timetaken=timer(1);
printf(“I- %f\n”,timetaken);
timetaken=timer(0);
for (i=1;i<=1e9;i++){i3=i1*i2;}
timetaken=timer(1);
printf(“I* %f\n”,timetaken);
timetaken=timer(0);
for (i=1;i<=1e9;i++){i3=i1/i2;}
timetaken=timer(1);
printf(“I/ %f\n”,timetaken);
printf(“\n”);
timetaken=timer(0);
for (i=1;i<=1e9;i++){d3=d1+d2;}
timetaken=timer(1);
printf(“D+ %f\n”,timetaken);
timetaken=timer(0);
for (i=1;i<=1e9;i++){d3=d1-d2;}
timetaken=timer(1);
printf(“D- %f\n”,timetaken);
timetaken=timer(0);
for (i=1;i<=1e9;i++){d3=d1*d2;}
timetaken=timer(1);
printf(“D* %f\n”,timetaken);
timetaken=timer(0);
for (i=1;i<=1e9;i++){d3=d1/d2;}
timetaken=timer(1);
printf(“D/ %f\n”,timetaken);
system(“PAUSE”);
return(0);
}
Feel free to post your own times, links of timings or other comments in the comments.
I will now look at memory jumping speed.
