Reputation:
Does anyone know why the same piece of code, executed twice, seems to be executed faster the first time than the second time?
I tried the code bellow about 20 times, every time the first execution was faster than the second one.
#include <iostream>
#include <time.h>
void add(int* var) {(*var)++;}
int main()
{
int var = 0;
clock_t tStart;
tStart = clock();
for(int i=450000000;i--;) {add(&var);}
printf("%.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
tStart = clock();
for(int i=450000000;i--;) {add(&var);}
printf("%.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
return 0;
}
It is really tiny, but still why is there a difference?
1.28s
1.36s
Program ended with exit code: 0
Would I have done something wrong? Maybe has it something to do with how I am timing the thing rather than with the speed of execution?
Thanks
Upvotes: 3
Views: 510
Reputation:
As suggested in the comments below the question, turning optimization off solved the problem.
Upvotes: -1
Reputation: 1341
There could be a million reasons why the speed of the execution was slightly different. It could have ran at the same time the system was doing some maintenance, the system could have outsourced the same thread to other processes, etc.
Also, using clock()
to measure for performance is not accurate, as it does not really measure time, but rather CPU cycles. I would recommend using std::chrono::high_resolution_clock
. An example of usage can be found here.
Upvotes: 1