Search code examples
c++clinuxmanpagegettimeofday

gettimeofday() - Why use both seconds and microseconds?


I need to use the function gettimeofday for a home assignment, and after reading the man page and looking some online examples, I can't see why people sometimes use both the tv_sec member of the struct and tv_usec member of the struct. The man page states:

  The tv argument is a struct timeval (as specified in <sys/time.h>):

       struct timeval {
           time_t      tv_sec;     /* seconds */
           suseconds_t tv_usec;    /* microseconds */
       };

So, assuming I need to return time in nanoseconds and I have created two timeval structs, start & end and I logged their time with gettimeofday(). Naturally my first thought was to calculate the difference in microseconds, i.e. start.tv_usec-end.tv_usec and then multiply it by 1000 to convert it into nanoseconds.

However, many online examples and tutorials calculate both the differences of the seconds and microseconds, convert them and then add them. (e.g.)

I read through the entire man page and couldn't find out why, would appreciate an explanation, if there is any.


Solution

  • The "microseconds" field doesn't have enough space to store all the time that passed. The "seconds" field is not precise enough. Together, they provide the most information.