【问题标题】:why is representation type for chrono::nanoseconds a signed integer type?为什么 chrono::nanoseconds 的表示类型是有符号整数类型?
【发布时间】:2017-02-15 10:20:09
【问题描述】:

在 /usr/include/c++/4.8 文件中的 gcc 4.84 中,我们有

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

为什么纳秒的表示类型是有符号整数类型?为什么没有签名?我们什么时候可以有一个负值的持续时间对象?

【问题讨论】:

  • 当你从过去的一个时间点中减去一个时间点。
  • 也许负持续时间可以代表某个时间点的before

标签: c++ std chrono


【解决方案1】:

我们什么时候可以有一个负值的持续时间对象?

任何时候你想代表负持续时间!

例如“十秒前”将是std::chrono::seconds(-10),如果你将它添加到一些time_point t,那么你会得到一个time_point,它比t早十秒。

标准规定“duration 类型测量两个时间点 (time_points) 之间的时间。”它并不是说它只能测量非递减时间点之间的时间。这意味着它可以用来测量t1t2 之间的时间,即使t2 &lt; t1 也是如此。要做到这一点,您需要一个负值。

如果无法对持续时间进行签名,则要表示表示“较早”而不是“较晚”的偏移量,您必须使用std::pair&lt;bool, duration&gt; 之类的东西,其中bool 表示它是正偏移还是负偏移,然后你必须这样做:

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;
}

这很愚蠢。通过使用有符号整数,语言和硬件已经更有效地支持这一点。

【讨论】:

  • 感谢您的回答。
【解决方案2】:

如果定义了两个对象ab,使得a - b 是一个持续时间,那么最好有a - b = -(b - a)

要实现该反交换属性,需要对持续时间进行签名。

【讨论】:

    【解决方案3】:

    不只是gcc实现,标准要求([time.syn]):

    typedef duration<signed integer type of at least 64 bits,        nano> nanoseconds;
    

    duration表示两个时间点A和B之间的时间差。如果A > B,则duration为正,否则为负,所以很有意义。

    【讨论】:

      猜你喜欢
      • 2018-12-18
      • 1970-01-01
      • 2020-04-15
      • 2011-06-29
      • 1970-01-01
      • 2011-07-06
      • 2021-08-17
      相关资源
      最近更新 更多