Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Signed and unsigned `rep` in `std::chrono` clocks

Tags:

c++

std

chrono

The rep type of std::chrono::system_clock is required to be a signed arithmetic type, whereas steady_clock and high_resolution_clock (and custom clock types) are not required to have a signed rep type.

What is the rationale for this distinction, and what would be the consequences of a clock using an unsigned rep type?

like image 561
Jeremy Avatar asked Sep 25 '18 10:09

Jeremy


1 Answers

The rationale was to allow vendors a little more freedom for steady_clock and high_resolution_clock. In hindsight, that freedom wasn't necessary as all implementations to date use signed integral types.

The consequences of using an unsigned rep in these clocks is that their duration nested type would not be one of the six "predefined" durations:

nanoseconds
microseconds
milliseconds
seconds
minutes
hours

As these are required to be signed. Also clients of a clock using an unsigned rep would have to be careful about subtracting time_points from that clock: subtracting t0 - t1 when t0 < t1 would result in an unsigned overflow value: Well defined, but potentially unexpected.

Such a clock can be used safely, and there do exist use cases for the unsigned overflow. But it would likely be more error prone in general.

The reason this latitude was not extended to system_clock was that it was hoped that system_clock would track Unix Time, and I wanted to require that datetimes prior to 1970-01-01 00:00:00 UTC be representable in system_clock::time_point. system_clock is the one clock that is required to be relatable to human calendars.

In the draft C++20 spec, the Unix Time relationship will finally be specified, and it will be much easier to convert between system_clock::time_point and the civil calendar, including datetimes prior to 1970-01-01 00:00:00 UTC.

But steady_clock remains a "stopwatch": Very good for timing things, but no relationship whatsoever to human calendars.

like image 51
Howard Hinnant Avatar answered Nov 16 '22 06:11

Howard Hinnant