std::chrono 纪元是什么时候?

When is std::chrono epoch?

std::chrono::time_point::time_since_epoch()returns一个duration,过去指代一些time_point。什么时候有这么一个time_point?它取决于 C++ 实现还是由 C++ 标准定义?或者将纪元设置为 1970 年 1 月 1 日 UTC 是事实上的标准?

它是 time_point 所指的特定 clockclock 的实现的函数。该标准规定了三种不同的时钟:

  • system_clock
  • steady_clock
  • high_resolution_clock

并且标准没有指定任何这些时钟的纪元。

程序员(您)也可以编写自己的时钟,这些时钟可能指定也可能不指定纪元。

有一个事实上的(非官方)标准,std::chrono::system_clock::time_point 的纪元与 Unix Time 一致。这定义为自 00:00:00 协调世界时 (UTC),星期四,1970 年 1 月 1 日以来经过的持续时间,不包括闰秒。

Fwiw,here is a date/time library 它利用了这个事实上的标准。

其他两个 std 指定的时钟没有事实上的标准。另外 high_resolution_clock 被允许作为 system_clocksteady_clock.

的类型别名

在 OS X 上,high_resolution_clocksteady_clock 的类型别名,steady_clock 是自计算机启动以来的纳秒计数(与 UTC 没有任何关系).

更新

C++2a 规范草案现在针对 system_clock:

Objects of type sys_time<Duration> measure time since (and before) 1970-01-01 00:00:00 UTC excluding leap seconds. This measure is commonly referred to as Unix time. This measure facilitates an efficient mapping between sys_timeand calendar types (27.8). [Example: sys_seconds{sys_days{1970y/January/1}}.time_since_epoch() is 0s. sys_seconds{sys_days{2000y/January/1}}.time_since_epoch() is 946’684’800s, which is 10’957 * 86’400s. —end example]

此外,C++2a 引入了utc_clocktai_clockgps_clockfile_clock。这些时钟也有明确定义的纪元,因为可以 clock_cast time_point 从一个时钟到另一个时钟,并且 system_clock.

file_clock 纪元不可移植,但您仍然可以将其 time_point 与民用历相关联。

utc_clock 类似于 system_clock,只是它不忽略闰秒。例如:

#include <chrono>
#include <iostream>

int
main()
{
    using namespace std::chrono;
    auto s1 = sys_days{December/31/2016} + 23h + 59min + 59s;
    auto s2 = sys_days{January/1/2017};
    auto u1 = clock_cast<utc_clock>(s1);
    auto u2 = clock_cast<utc_clock>(s2);
    std::cout << s2 - s1 << '\n';
    std::cout << u2 - u1 << '\n';
}

输出:

1s
2s

更新

Link 到现在指定的 (C++20) system_clock 纪元:http://eel.is/c++draft/time.clock.system#overview-1

Objects of type system_­clock represent wall clock time from the system-wide realtime clock. Objects of type sys_­time<Duration> measure time since 1970-01-01 00:00:00 UTC excluding leap seconds. This measure is commonly referred to as Unix time. This measure facilitates an efficient mapping between sys_­time and calendar types ([time.cal]). [ Example: sys_­seconds{sys_­days{1970y/January/1}}.time_­since_­epoch() is 0s. sys_­seconds{sys_­days{2000y/January/1}}.time_­since_­epoch() is 946'684'800s, which is 10'957 * 86'400s. — end example ]