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?
Share
For C++03:
Boost.Timer might work, but it depends on the C function
clockand so may not have good enough resolution for you.Boost.Date_Time includes a
ptimeclass that’s been recommended on Stack Overflow before. See its docs onmicrosec_clock::local_timeandmicrosec_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_counterthat exists in both thewinstlandunixstlnamespaces, then use whichever namespace matches your platform.)For C++11 and above:
The
std::chronolibrary has this functionality built in. See this answer by @HowardHinnant for details.