关于c ++:std :: chrono :: time_point设置为现在

std::chrono::time_point set to now

我对std :: chrono上的库和文档还很陌生,对我来说不起作用。

我正在尝试实现包含时间戳记的对象的容器。这些对象将按从最新到最近的顺序存储,我决定尝试使用std :: chrono :: time_point表示每个时间戳。处理数据的线程将定期唤醒,处理数据,查看何时需要再次唤醒,然后在该时间内休眠。

1
static std::chrono::time_point<std::chrono::steady_clock, std::chrono::milliseconds> _nextWakeupTime;

我的印象是上面的声明使用了毫秒级的固定时钟。

下一步是将_nextWakeupTime设置为now;

1
_nextWakeupTime = time_point_cast<milliseconds>(steady_clock::now());

那行不会编译:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::chrono::time_point<_Clock,_Duration>' (or there is no acceptable conversion)
        with
        [
            _Clock=std::chrono::system_clock,
            _Duration=std::chrono::milliseconds
        ]
        chrono(298): could be 'std::chrono::time_point<_Clock,_Duration> &std::chrono::time_point<_Clock,_Duration>::operator =(const std::chrono::time_point<_Clock,_Duration> &)'
        with
        [
            _Clock=std::chrono::steady_clock,
            _Duration=std::chrono::milliseconds
        ]
        while trying to match the argument list '(std::chrono::time_point<_Clock,_Duration>, std::chrono::time_point<_Clock,_Duration>)'
        with
        [
            _Clock=std::chrono::steady_clock,
            _Duration=std::chrono::milliseconds
        ]
        and
        [
            _Clock=std::chrono::system_clock,
            _Duration=std::chrono::milliseconds
        ]

我了解在Windows系统上,stead_clock与system_clock是同一件事,但是我不知道这里发生了什么。我知道我可以这样做:

1
_nextWakeupTime += _nextWakeupTime.time_since_epoch();

我只是觉得这不代表我应该做的事。

同样,实例化给定时钟/持续时间的time_point对象并将其设置为现在的最佳方法是什么?


您要做的最简单的事情是给_nextWakeupTime类型输入steady_clock::time_point

1
steady_clock::time_point _nextWakeupTime;

您可以使用steady_clock::time_point::period查询该time_point的分辨率,在此情况下您将得到具有静态成员numdenstd::ratio

1
2
3
4
typedef steady_clock::time_point::period resolution;
cout <<"The resolution of steady_clock::time_point is" << resolution::num
     << '/' <<resolution::den <<" of a second.
"
;

从您的错误消息中可以看出,您的供应商已将system_clock::time_pointsteady_clock::time_point设置为相同的time_point,因此它们共享相同的纪元,您可以在算术中将二者混用。 为了方便地处理这种情况,您可以使用以下命令查询time_point的时钟:

1
time_point::clock

即 在您的实现中,steady_clock::time_point::clock不是steady_clock,而是system_clock。 如果您确实想要与steady_clock::time_point兼容但具有毫秒分辨率的time_point,则可以执行以下操作:

1
time_point<steady_clock::time_point::clock, milliseconds> _nextWakeupTime;