c++ - 两个纳秒 chrono::time_points 之间的差异,但以秒为单位?

标签 c++ c++11 c++-chrono

我有一个时间戳(自纪元以来的纳秒数):

uint64_t ts = .....;

我想检查它是否比当前系统时间早 5 秒以上。

所以我需要将时间戳转换为 time_point?然后从当前时间(以纳秒为单位)中减去它,检查它的值是否大于 chrono::duration::seconds(5)?

到目前为止:

const std::chrono::time_point tstp(std::chrono::duration_cast<std::chrono::nanoseconds>(rawNanos));
const std::chrono::time_point now = std::chrono::high_resolution_clock::now();

const bool old = now - tstp > std::chrono::seconds(5);

但由于 time_point 的构造函数类型而苦苦挣扎。

最佳答案

您不应为此使用 high_resolution_clock。在某些平台上,high_resolution_clock 计算自计算机启动以来的时间,而不是自 Unix 纪元以来的时间。

虽然标准没有指定,但事实上的标准是在所有平台上,system_clock 计算自 Unix 纪元以来的时间。

我发现首先声明一个模板化类型别名很方便,它是一个基于 system_clocktime_point,在 duration 上模板化。这使得创建自 Unix 纪元以来计算时间的任意精度的 time_point 变得容易:

template <class D>
using sys_time = std::chrono::time_point<std::chrono::system_clock, D>;

鉴于:

uint64_t ts = 1235;
using namespace std::chrono;
const bool old =  system_clock::now() >
                      sys_time<nanoseconds>{nanoseconds{ts}} + seconds{5};

在 C++14 中,您将能够编写:

const bool old =  system_clock::now() >
                      sys_time<nanoseconds>{nanoseconds{ts}} + 5s;

关于c++ - 两个纳秒 chrono::time_points 之间的差异,但以秒为单位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41611690/

相关文章:

c++ - move 构造函数可以接受类本身以外的参数吗?

C++从已实现的虚拟类调用非虚拟方法

c++ - 在 C++ 中从 Linux 应用程序发送电子邮件

c++ - 如何找到纪元时间戳和 std::chrono::system_clock::now 之间以毫秒为单位的时差

c++ - CMake 的 VS_PACKAGE_REFERENCES 未添加对 VS2017 项目的引用

c++ - 关于指针取消引用的 C/C++ 问题

c++ - 氧气错误 : Found ';' while parsing initializer list

C++ exponential_distribution模板类生成非精确随机数

c++ - 如何为没有值的已声明 std::chrono::duration 赋值?

c++ - 将 uint64_t 转换为 time_point