std::chrono::duration 剩余时间测量溢出

Overflow in std::chrono::duration for remaining time measurement

我想知道事件发生还有多长时间。我为此使用 boost::chrono 或 std::chrono。

基本上算法是这样的:

using std::chrono; // Just for this example
auto start = steady_clock::now();
seconds myTotalTime(10);
while(true){
  auto remaining = start + myTotalTime - steady_clock::now();
  seconds remainingSecs = duration_cast<seconds>(remaining);
  if(remainingSecs.count() <= 0) return true;
  else print("Remaining time = " + remainingSecs.count()); // Pseudo-Code!
}

现在(理论上)可能会发生以下情况:start 接近时钟周期的末尾(IMO 没有概念 0 是什么意思,所以它可能是任意的)。
然后 start + myTotalTime 可能会溢出并且减法可能会下溢。

即使像 steady_clock::now() - start 这样简单的事情也可能下溢。

对于无符号类型,这不是问题。如果它们是无符号的,那么标准保证在溢出 now() 和下溢减法的情况下,我仍然为 steady_clock::now() - start 获得正确数量的 "units":10 - 250 = 10 + 256 - 255 = 16 8 位无符号数学。

但是 AFAIK over/underflow 对于签名类型是未定义的行为。

我错过了什么吗?为什么持续时间,尤其是 time_points 是用有符号而不是无符号类型定义的?

我没有看到问题。您选择的单位不会超出您的需要,对吗?

在我的系统上(是的,我知道,但是)std::chrono::seconds 被定义为 int64_t,所以假设选择了一个合理的纪元(!=大爆炸),它不会溢出任何时间很快。

其他的也一样,但是在纳秒内擦掉 30 位,很有可能溢出,剩下的 33 位 /only/ 270 年左右。

time_point 在内部使用持续时间,因为它是自纪元以来的持续时间。原则上,如果你的纪元是 1970 (Unix),你可能想参考之前的日期,所以它必须被签名。如果你的epoch是1600(Windows),你显然不能用纳秒来表示当前时间点,这是一个可移植性问题。

当然,您可以使用 double 定义自己的持续时间,其中范围与分辨率交换,我过去曾这样做过,作为打印十进制秒时间戳的便捷方式。

或者如果您需要范围和分辨率,您可以定义一个更大的整数 class。

这是一个简短的程序,您可以使用它查看任何平台在 steady_clock 中剩余的范围(相对于现在):

#include <chrono>
#include <iostream>

int
main()
{
    using namespace std::chrono;
    using namespace std;
    using days = duration<int, ratio<86400>>;
    using years = duration<double, ratio_multiply<ratio<146097, 400>, days::period>>;
    cout << years{steady_clock::time_point::max() -
                  steady_clock::now()}.count() << " years to go\n";
}

这将输出从现在起 steady_clock 溢出的年数。在几个不同的平台上 运行 这几次之后,你应该会有一种温暖的模糊感觉,除非你的程序要 运行 超过几百年,否则你不需要担心。

在我的平台上(这很常见),steady_clock 以纳秒为单位测量启动后的时间。

对我来说这个程序输出:

292.127 years to go

任何不能代表now()无溢出的平台和任何时钟都不太可能被广泛采用。

Why are the duration and especially time_points defined with signed instead of unsigned types?

  • 使 durationtime_point 减法不易出错。是的,如果你减去 unsigned_smaller - unsigned_larger 你会得到一个定义明确的结果,但那个结果不是可能是程序员期望的答案(除了 time_point + 您给出的持续时间的示例)。

  • 因此 1970 年之前的日期时间可以用 system_clock::time_point 表示。尽管未指定,但 system_clock 正在测量 Unix Time(使用各种精度)是事实上的标准。这需要保持负值来表示 1970-01-01 00:00:00 UTC 之前的时间。我目前正在尝试将这种现有做法标准化。

取而代之的是,用足够的位数指定了有符号整数表示,以试图使溢出成为一个罕见的问题。纳秒精度保证有 +/- 292 年的范围。较粗的精度将具有比这更大的范围。当此默认值不够时,允许自定义表示。