Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Using High-resolution Timers : Page 2

For multimedia streaming, games, and profiling, Standard C++'s time-meausurement facilities are limited. For high-resolution timers, look to the POSIX libraries

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> header:

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:

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

The following code listing obtains the current timestamp using gettimeofday() and displays it onscreen:

#include <sys/time.h> #include <iostream> int main() { struct timeval tv; gettimeofday(&tv,0); std::cout<<"the current timestamp is: " <<tv.tv_sec<<"."<<tv.tv_usec<<std::endl; }

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.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date