I am trying to measure CPU time using following code.
timespec time1, time2, temp_time;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
int i;
int cpu_sum = 0;
for (i = 0; i < nelements; i++) {
cpu_sum += array[i];
}
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);
temp_time.tv_sec = time2.tv_sec - time1.tv_sec;
printf( sum: %d using CPU in %lf ms \n",cpu_sum, temp_time.tv_sec);
But I always get time as 0.000ms
Any idea what is wrong here.
Any help would be appreciated.
Thanks
You’re invoking undefined behavior by passing the wrong argument types to
printf(time_t, which is probablylong, instead ofdouble).tv_secjust contains the whole seconds part of the time. You need to also usetv_nsecto get the nanoseconds part.Try something like: