I'm looking to implement a simple timer mechanism in C++. The code should work in Windows and Linux. The resolution should be as precise as possible (at least millisecond accuracy). This will be used to simply track the passage of time, not to implement any kind of event-driven design. What is the best tool to accomplish this?
For C++03:
Boost.Timer might work, but it depends on the C function clock
and so may not have good enough resolution for you.
Boost.Date_Time includes a ptime
class that's been recommended on Stack Overflow before. See its docs on microsec_clock::local_time
and microsec_clock::universal_time
, but note its caveat that "Win32 systems often do not achieve microsecond resolution via this API."
STLsoft provides, among other things, thin cross-platform (Windows and Linux/Unix) C++ wrappers around OS-specific APIs. Its performance library has several classes that would do what you need. (To make it cross platform, pick a class like performance_counter
that exists in both the winstl
and unixstl
namespaces, then use whichever namespace matches your platform.)
For C++11 and above:
The std::chrono
library has this functionality built in. See this answer by @HowardHinnant for details.