这样做是为了让您获得最大的灵活性和紧凑的尺寸。如果需要超精细的精度,通常不需要很大的范围。如果您需要非常大的范围,通常不需要非常高的精度。
例如,如果您以纳秒为单位进行交易,您是否经常需要考虑超过 +/- 292 年?如果你需要考虑比这个更大的范围,那么微秒可以给你+/- 292thousand years.
苹果系统system_clock
实际上返回微秒,而不是纳秒。那么这个时钟从1970年开始可以运行29.2万年,直到溢出。
窗户system_clock
精度为 100 纳秒单位,因此范围为 +/- 29,200 年。
如果几十万年还不够,可以尝试毫秒。现在你的范围是+/- 292million years.
最后,如果你只是have纳秒精度可以持续数百年,<chrono>
还允许您自定义存储:
using dnano = duration<double, nano>;
这为您提供了存储为纳秒的double
。如果您的平台支持 128 位整数类型,您也可以使用它:
using big_nano = duration<__int128_t, nano>;
哎呀,如果你为timespec
,你甚至可以使用that用于存储(但我不推荐)。
您还可以实现比纳秒更精细的精度,但这样做会牺牲范围。例如:
using picoseconds = duration<int64_t, pico>;
其范围仅为 +/- 0.292 年(几个月)。那么你do必须小心这一点。如果您有一个可以提供亚纳秒精度的源时钟,那么非常适合计时。
查看这个视频 https://www.youtube.com/watch?v=P32hvk8b13M欲了解更多信息<chrono>
.
为了创建、操作和存储范围大于当前公历有效性的日期,我创建了这个开源日期库 https://howardhinnant.github.io/date/date.html这扩展了<chrono>
提供日历服务的图书馆。该库以带符号的 16 位整数存储年份,因此范围为 +/- 32K 年。它可以这样使用:
#include "date.h"
int
main()
{
using namespace std::chrono;
using namespace date;
system_clock::time_point now = sys_days{may/30/2017} + 19h + 40min + 10s;
}
Update
在下面的评论中提出了如何“标准化”的问题duration<int32_t, nano>
转换为秒和纳秒(然后将秒添加到 time_point)。
首先,我对将纳秒填充到 32 位中持谨慎态度。该范围仅略高于 +/- 2 秒。但我是这样区分单位的:
using ns = duration<int32_t, nano>;
auto n = ns::max();
auto s = duration_cast<seconds>(n);
n -= s;
请注意,这仅在以下情况下有效n
是积极的。正确处理负面情绪n
,最好的做法是:
auto n = ns::max();
auto s = floor<seconds>(n);
n -= s;
std::floor
是随 C++17 引入的。如果你想早点拿到,可以从here http://howardhinnant.github.io/duration_io/chrono_util.html or here https://github.com/HowardHinnant/date/blob/master/date.h.
我偏爱上面的减法运算,因为我发现它更具可读性。但这也有效(如果n
不是负数):
auto s = duration_cast<seconds>(n);
n %= 1s;
The 1s
在 C++14 中引入。在 C++11 中,您必须使用seconds{1}
反而。
一旦你有几秒钟(s
),您可以将其添加到您的time_point
.