Getting Negative Values Using clock_gettime

江枫思渺然 提交于 2021-02-04 13:50:16

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!