In the following program, I have tried to measure the execution time of a job(for loop). Most of the time it works fine, however, sometimes, it returns negative values!! My first guess is that the variable may get overflowed. Can anyone please let me whether I am right or not? How can I solve the problem?
Thanks
int main(int argc, char **argv)
{
long int ST;
long int ET;
struct timespec gettime_now;
clock_gettime(CLOCK_REALTIME, &gettime_now);
ST= gettime_now.tv_nsec;
for (i=0; i < 1000; i++)
a[i]=b[i];
clock_gettime(CLOCK_REALTIME, &gettime_now);
ET= gettime_now.tv_nsec;
printf("Time diff: %ld\n", ET-ST);
}
You are neglecting tv_sec
of struct timespec
in both the cases and just using nano-second which is not correct as ST
and EV
's tv_nsec may be of different second's.
From man,
tv_sec
- represents seconds since epoch
tv_nsec
- current second in nano-second precision (1/1000000000 sec)
It is better to write own function to find the difference. Sample code (not tested),
timespec diff(timespec start, timespec end)
{
timespec temp;
if ((end.tv_nsec-start.tv_nsec)<0
{
temp.tv_sec = end.tv_sec-start.tv_sec-1;
temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
}
else
{
temp.tv_sec = end.tv_sec-start.tv_sec;
temp.tv_nsec = end.tv_nsec-start.tv_nsec;
}
return temp;
}
Refer this for actual diff
function and example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With