When is std::chrono epoch?

ぐ巨炮叔叔 提交于 2020-01-09 06:47:39

问题


std::chrono::time_point::time_since_epoch() returns a duration, referred to some time_point in the past. When is such a time_point? It depends on the C++ implementation or it's defined by the C++ standard? Or it is a de facto standard to set the epoch to 1 January 1970 UTC?


回答1:


It is a function of both the specific clock the time_point refers to, and the implementation of that clock. The standard specifies three different clocks:

  • system_clock
  • steady_clock
  • high_resolution_clock

And the standard does not specify the epoch for any of these clocks.

Programmers (you) can also author their own clocks, which may or may not specify an epoch.

There is a de-facto (unofficial) standard that std::chrono::system_clock::time_point has an epoch consistent with Unix Time. This is defined as the time duration that has elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, not counting leap seconds.

Fwiw, here is a date/time library which takes advantage of this de-facto standard.

There is no de-facto standard for the other two std-specified clocks. Additionally high_resolution_clock is permitted to be a type alias for either system_clock or steady_clock.

On OS X, high_resolution_clock is a type alias for steady_clock, and steady_clock is a count of nanoseconds since the computer booted (no relationship whatsoever to UTC).

Update

The draft C++2a spec now says for 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]

Additionally, C++2a introduces utc_clock, tai_clock, gps_clock and file_clock. These clocks also have well-defined epochs as one can clock_cast time_points from one clock to another among these and system_clock.

The file_clock epoch will not be portable, but you will still be able to relate its time_points to the civil calendar.

utc_clock is like system_clock, except that it does not ignore leap seconds. For example:

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

Outputs:

1s
2s


来源:https://stackoverflow.com/questions/29799293/when-is-stdchrono-epoch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!