I'm trying to optimize a chunk of code given to me by a friend but my baseline for average execution times of it are extremely erratic and I'm lost to as why/how to fix it.
Code:
#include <sys/time.h> #include <time.h> #include <stdio.h> #include "wall.h" /* Where his code is */ int main() { int average; struct timeval tv; int i; for(i = 0; i < 1000; i++) /* Running his code 1,000 times */ { gettimeofday(&tv, NULL); /* Starting time */ start(); /* Launching his code */ int ret = tv.tv_usec; /* Finishing time */ ret /= 1000; /* Converting to milliseconds */ average += ret; /* Adding to the average */ } printf("Average execution time: %d milliseconds\n", average/1000); return 0; } Output of 5 different runs:
- 804 milliseconds
- 702 milliseconds
- 394 milliseconds
- 642 milliseconds
- 705 milliseconds
I've tried multiple different ways of getting the average execution time, but each one either doesn't give me a precise enough answer or gives me a completely erratic one. I'm lost as to what to do now, any help would be greatly appreciated!
I know these types of benchmarks are very much system dependent, so I've listed my system specs below:
- Ubuntu 12.10 x64
- 7.8 GiB RAM
- Intel Core i7-3770 CPU @ 3.40GHz x 8
- GeForce GT 620/PCIe/SSE2
Edit
Thank you all for your input but I decided to go with a gprof instead of constructing my own. Thank you, once again!
tv_usecmember of thetimevalstructure contains the microsecond part of the current time, not the number of microseconds since the Epoch. You are not measuring the execution time but rather sampling the microseconds part. The observed distribution of the value is quite normal (no pun intended).gettimeofday()was called".