Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is representation type for chrono::nanoseconds a signed integer type?

In gcc 4.84 in file /usr/include/c++/4.8 we have

namespace std  
{
   typedef duration<int64_t, nano>     nanoseconds;

Why is the representation type for nanosecond a signed integer type? Why isn't it unsigned? when can we have a duration object with a negative value ?

like image 235
MichaelMoser Avatar asked Sep 15 '25 04:09

MichaelMoser


2 Answers

when can we have a duration object with a negative value ?

Any time you want to represent a negative duration!

e.g. "Ten seconds earlier" would be std::chrono::seconds(-10) and if you add that to some time_point t then you get a time_point that is ten seconds before t.

The standard says "A duration type measures time between two points in time (time_points)." It doesn't say that it can only measure time between non-decreasing time points. So that means it can be used to measure the time between t1 and t2 even if t2 < t1. And to do that simply, you need a negative value.

If durations couldn't be signed then, to represent an offset that means "earlier" not "later", you'd have to use something like std::pair<bool, duration> where the bool says whether it's a positive or negative offset, and then you'd have to do:

chrono::time_point adjust(chrono::time_point t, pair<bool, duration> offset)
{
  if (offset.first)  // positive
    return t + offset.second;
  else // negative
    return t - offset.second;
}

This is dumb. The language and the hardware already support this far more expressively and efficiently, by using signed integers.

like image 62
Jonathan Wakely Avatar answered Sep 16 '25 17:09

Jonathan Wakely


If two objects a and b are defined such that a - b is a duration, then it's desirable to have a - b = -(b - a).

To implement that anti-commutative property, the duration needs to be signed.

like image 39
Bathsheba Avatar answered Sep 16 '25 17:09

Bathsheba