问题
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);
}
回答1:
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.
来源:https://stackoverflow.com/questions/17705786/getting-negative-values-using-clock-gettime