This is related to my previous question where I asked if std::chrono::steady_clock::now
should be noexcept
. Now that I know that it should I wonder how does this function report errors? For example, a common implementation of this function on Linux uses
clock_gettime which can return an error.
2 Answers
All of the errors that could be reported by the Linux clock_gettime
facility are not possible in a debugged implementation of std::chrono::steady_clock::now()
.
The errors are:
int clock_gettime(clockid_t clk_id, struct timespec *tp);
EFAULT
tp points outside the accessible address space.
There is no user-supplied tp
to get wrong in std::chrono::steady_clock::now()
. If std::chrono::steady_clock::now()
passes the wrong tp
to clock_gettime
, it is just a bug in steady_clock
that is easily fixed.
EINVAL
The clk_id specified is not supported on this system.
There is no user-supplied clk_id
to get wrong in std::chrono::steady_clock::now()
. If std::chrono::steady_clock::now()
passes the wrong clk_id
to clock_gettime
, it is just a bug in steady_clock
that must be fixed.
Note that an implementation of steady_clock
isn't guaranteed to be portable, and may have to be ported to any given platform and be tested for correctness. It might turn out that steady_clock
can not be implemented in terms of clock_gettime
on some platforms.
EPERM
clock_settime() does not have permission to set the clock indicated.
Not applicable to steady_clock
as there is no API to set the time.

- 206,506
- 52
- 449
- 577
-
Thanks a lot for the answer. What about Windows where the clock is normally implemented using QueryPerformanceCounter which can return an the documentation doesn't seem to enumerate the error cases? – vitaut Aug 07 '13 at 18:12
-
1Sorry, I'm not familiar with Windows. I do see this LWG issue, currently in status NAD Future: http://cplusplus.github.io/LWG/lwg-closed.html#935 – Howard Hinnant Aug 07 '13 at 18:27
It doesn't. There's no provision in the API for error reporting. So the Linux implementation must either handle errors internally or not return (e.g., via exit()
or std::terminate()
).

- 41,449
- 7
- 95
- 125
-
An implementation could also store the last successful value and just return it in case it cannot access a real clock. This satisfies the monotonic requirement of `steady_clock`. I have no idea if any implementations actually do this. – GManNickG Aug 07 '13 at 17:59
-
1@GManNickG That would fall under the heading of "handle errors internally" - but it would not conform (at least in principle) to the requirement that "values of `time_point` advance at a steady rate relative to real time." from 20.11.7.2/1 [time.clock.steady]. – Casey Aug 07 '13 at 18:04