[英]How to convert std::chrono::time_point to std::tm without using time_t?
[英]std::chrono time_t conversions overflow?
我的示例代码:
time_t time_tee = 253402210800;
auto tp = std::chrono::system_clock::from_time_t(time_tee);
time_t tee2 = std::chrono::system_clock::to_time_t(tp);
std::cout << tee2 << std::endl;
期望:输出 2534022108 输出:-4852206231
time_t 是 64 位,所以不应该有溢出。
我在这里触发了什么样的溢出?
问题是system_clock
时间分辨率。
这段代码:
#include <chrono>
#include <iostream>
int main()
{
using std::chrono::system_clock;
time_t time_tee = 253402210800;
auto tp = system_clock::from_time_t(time_tee);
time_t tee2 = system_clock::to_time_t(tp);
std::cout << time_tee << std::endl;
std::cout << tee2 << std::endl;
std::cout << system_clock::period::num << std::endl;
std::cout << system_clock::period::den << std::endl;
return 0;
}
在MSVC 打印上:
253402210800
253402210800
1
10000000
253402210800
-4852206231
1
1000000000
因此,正如您所看到的,GCC 和 Clang 使用的system_cloc
分辨率提高了 100 倍。 请注意,这也是比time_t
提供的分辨率更好的分辨率,并且成本是更有限的时间范围。
glibc
system_clock::duration
使用chrono::nanoseconds
来存储时间点。 chrono::nanoseconds
是int64_t
。
因为:
253402210800 seconds = 253402210800000000000 nanoseconds
INT64_MAX = 922337203685477580
glibc 上的计算溢出。
我在标准草案中没有看到对system_clock::rep
任何限制,只是应该对其进行签名。
我在这里触发了什么样的溢出?
有符号溢出发生在system_clock::from_time_t(time_tee);
当在time_point_cast<system_clock::duration>
内将time_t
为system_clock::duration
时,将253402210800
乘以1000000000
时。 我认为这正好在__duration_cast_impl
。
我认为您应该通过支票防止溢出,例如:
static_assert(
std::chrono::duration_cast<std::chrono::seconds>
(std::chrono::system_clock::duration::max()).count() > 253402210800
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.