Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Negative Values Using clock_gettime

Tags:

c

time

clock

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);
}
like image 220
user2517676 Avatar asked Jul 17 '13 16:07

user2517676


1 Answers

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.

like image 157
VoidPointer Avatar answered Nov 15 '22 07:11

VoidPointer