Time and time() Again
Applications that need a high-resolution time measurement can use the quasi-portable gettimeofday()
function defined by the POSIX standard and also available on most versions of Windows. gettimeofday()
is declared in the <sys/time.h>
int gettimeofday (struct timeval *tp, void*);
It writes to tp
the number of seconds that have elapsed since the epoch, i.e., 01/01/1970 00:00:00. Unlike time()
, which uses a one-second granularity, gettimeofday()
expresses the current timestamp in seconds and microseconds (millionths of a second) since the epoch. As with may other time-measuring functions, the actual resolution of gettimeofday()
depends on the underlying hardware of your machine, so you shouldn't assume that every platform supporting gettimeofday()
will necessarily have a microsecond granularity.
gettimeofday() writes the current timestamp into a timeval data structure:
time_t tv_sec; //seconds
suseconds_t tv_usec; //microseconds
The following code listing obtains the current timestamp using gettimeofday()
and displays it onscreen:
struct timeval tv;
std::cout<<"the current timestamp is: "
A granularity of one millionth of a second sounds impressive, yet some applications require even higher. Timers with a resolution of a nanosecond are now available on real-time POSIX systems.