Reputation: 3547
A problem with CLOCK_REALTIME is that it isn't monotonic and that time can potentially go backwards if a NTP sync occurred.
Would it be safe to do something like the following to make it monotonic?
struct timespec GetMonotonicTime()
{
static struct timespec last = timespec();
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
last.tv_nsec = (last.tv_sec == ts.tv_sec) ? std::max(last.tv_nsec, ts.tv_nsec) : ts.tv_nsec;
last.tv_sec = std::max(last.tv_sec, ts.tv_sec);
return last;
}
Upvotes: 0
Views: 866
Reputation: 96261
In addition to having problems if ever run in a multi-threaded envinronment your ns
attribute will asymptote to 999999999 as time passes.
Linux provides CLOCK_MONOTONIC
if that happens to be your platform (and it would satisfy your needs).
Upvotes: 1