Saturday, March 25, 2006

How to speed your code in C++: int vs double & Global vs Local & Array vs two dimensional Array

Today, my main task is to speed up one of my algorithm. I am really novice in C++. I try seveal modifications.

int vs double
For example, change unnecessary double functions/parameter to int. If you really need double parameter like 1.2, you can compute based on 12. After finishing major computation, you can scale it correspondingly. It will save time especial when there is float multiplication.

global vs local variable
global variables really consume time.
For example, if you define a global variable

int c = 20;

% Then you do the loop in main()
for ( ni = 0; ni <=900000000; ni++)
x = c;

The seconds I got is 2.25, 2.4, 2.31, 2.21, 2.2, 2.27, 2.39

if you define a local variable in main()
Then the second consumed sample is 1.83, 1.83, 1.82, 1.83, 1.82, 1.82, 1.82

The gap is obvious. Another interesting thing is variance of first experiment is also significant.

One dimension array vs two dimension array
I create one dimension array and two dimension array with the same size.

int e[20000];
int d[40][500];

then I do the similar experiment 3
for ( ni = 0; ni <=900000000; ni++)
x = e[10000];
The seconds consumed is 1.83, 1.83, 1.82, 1.83, 1.82, 1.82, 1.82, 1.82

experiment 4
for ( ni = 0; ni <=900000000; ni++)
x = d[20][500];
The seconds consumed is 2.28, 2.27, 2.27, 2.32, 2.27, 2.21

It seems it is better to project two dimension array to one dimension array.

But in individual case, you need consider time of converting two dimension index to one dimension.

Finally, my code speeds up average by 15%.

Anyone can provide his experience about speeding up code?

No comments: