Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it guaranteed that std::chrono::steady_clock never wraps around?

Tags:

c++

c++11

chrono

Basically:

auto p1 = std::steady_clock::now().time_since_epoch().count();

... // do smth for unspecified period of time

auto p2 = std::steady_clock::now().time_since_epoch().count();

assert(p2 >= p1);   // is this guaranteed?

?

If yes -- how it this guaranteed? By making sure no C++ program ever runs for longer than std::steady_clock::duration::max() - std::steady_clock::duration::zero()?

like image 618
C.M. Avatar asked Oct 07 '20 21:10

C.M.


1 Answers

Like many things in this topical area, it's complicated...

Yes, it is guaranteed that steady_clock::now() never wraps, as it is guaranteed that it always increases:

http://eel.is/c++draft/time.clock.steady

Objects of class steady_­clock represent clocks for which values of time_­point never decrease as physical time advances and for which values of time_­point advance at a steady rate relative to real time. That is, the clock may not be adjusted.

But...

how it this guaranteed

Technically it is not possible to have a clock with finite memory tick forever and never run out of range. So technically, the answer is no.

But ...

As a practical manner, all implementations of steady_clock count nanoseconds using signed 64 bit integral types. The range on this is +/-292 years. And it is common for the epoch to be the last time your computer booted up. So practically, it won't wrap in your lifetime. Thus when it wraps, it will be somebody else's problem, and the computer involved will get some kind of award for having an uptime of that length of time.

PS: I can't wait for the computer manuals to come out that say:

Must be rebooted at least once every 292 years.

:-)

like image 96
Howard Hinnant Avatar answered Sep 30 '22 05:09

Howard Hinnant