I have following code snippet and i am trying to evaluate the time take by CPU
However I am getting some weird results
struct timeval begin, end;
double cpu_time=0.0;
gettimeofday(&begin, NULL);
long cpu_sum = 0;
for (i = 0; i < size; i++) {
cpu_sum += array[i] * array[i];
}
gettimeofday(&end, NULL);
cpu_time = end.tv_sec - begin.tv_sec * 1000;
cpu_time += (end.tv_usec - begin.tv_usec) / 1000;
printf("calculated sum: %d using CPU in %lf ms \n", cpu_sum, cpu_time);
Sample result = 1296217442.000000 ms
I dont think this is correct time value in ms.
Can anyone help whats wrong here?
Any help would be appreciated.
Thanks
If you want CPU time, you probably want to use
clock_gettimeinstead with theCLOCK_PROCESS_CPUTIME_IDparameter.That’s the probably most convenient (and accurate) way to get both real time and cpu time using the same function, only changing one parameter.