A portable C ++ solution would be to use chrono::steady_clock
to measure time. This is available in C ++ 11 under the <chrono>
header, but may be available to older compilers in TR1 in <tr1/chrono>
or boost.chrono .
Sustainable watches always advance at the speed of "as uniform as possible", which is an important factor on a multi-tasking multi-threaded platform. A stable clock is also independent of any βwall clockβ, for example, a system clock (which can be arbitrarily manipulated at any time).
(Note: if steady_clock
not part of your implementation, find monotonic_clock
.)
The <chrono>
types are a little distorted, so here is an example of a code fragment that returns a stable timestamp (more precisely, a timestamp from what you like, for example, high_resolution_clock
):
template <typename Clock> long long int clockTick(int multiple = 1000) { typedef typename Clock::period period; return (Clock::now().time_since_epoch().count() * period::num * multiple) / period::den; } typedef std::chrono::monotonic_clock myclock;
Using:
long long int timestamp_ms = clockTick<myclock>();
source share