cgettimeofday

C : Why startingTime is larger than endingTime with gettimeofday()?


I'd like to measure the computing time with while loop.

I'm programming with C99 version.

My code is below:

struct timeval startingTime,endingTime;
gettimeofday(&startingTime, NULL);
while(read(fd,&student,206) != 0){
    printf("%s\n",student);
}
gettimeofday(&endingTime, NULL);
long elapsed = endingTime.tv_usec-startingTime.tv_usec;
printf("Computing Time : %ld\n",elapsed);
printf("ending : %d , starting %d",endingTime.tv_usec,startingTime.tv_usec);

Then the result is below :

Computing Time : -76716

ending : 334481 , starting 411197

As you see, starting is bigger than ending...

I can not totally understand what I'm missing...

Is there anyone who knows this situation?


Solution

  • struct timeval has actually two members, a tv_sec member and a tv_usec member. tv_usec is the number of usec pass that tv_sec value, which is in seconds (as the name implies).

    So you have to check the tv_sec difference first, and than calculate the tv_usec difference (taking into account wraparound).

    What you are doing currently is similar to checking only the minutes differences when the duration was a couple of hours. The ending minutes might be greater then starting minutes, since the hour can have increased as well.