我试图通过查看数据的时间戳来查看我的数据是否是 120 秒(或 2 分钟)旧的,所以当我chrono
在 C++ 中使用包时,我有以下代码:
uint64_t now = duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
// check for 2 minutes old data
bool is_old = (120 * 1000 < (now - data_holder->getTimestamp()));
uint64_t value = now;
while (now < data_holder->getTimestamp() + 80 * 1000
&& now < value + 80 * 1000) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
now = duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
}
在上面的代码data_holder->getTimestamp()
中是 uint64_t,它以毫秒为单位返回时间戳。
现在当我打印出now
变量值时,我看到了这个10011360
,当我打印出data_holder->getTimestamp()
值时1437520382241
2015-07-21 16:13:02,530 WARN 0x7f35312d1700 data_check - now value: 10011360 , data holder timestamp: 1437520382241
从上面的数据持有者时间戳来看,它看起来不是 120 秒的旧数据,所以我觉得我的代码有问题?因为如果我将该数据持有者时间戳转换为实际时间(使用纪元转换器),然后将其与如上所示的日志时间进行比较,它几乎是相同的。
所以我决定使用system_clock
代替steady_clock
并想出了下面我开始使用auto
代替的代码uint64_t
。
解决方案 A:
auto now = system_clock::now();
auto dh_ts = system_clock::time_point{milliseconds{data_holder->getTimestamp()}};
bool is_old = (minutes{2} < (now - dh_ts));
早些时候,我使用now
变量值uint64_t
代替auto
. 现在在上面的代码之后,我的原始代码中有类似的东西,因为now
不是uint64_t
,所以我在编译代码时遇到了编译错误。
uint64_t value = now;
while (now < data_holder->getTimestamp() + 80 * 1000
&& now < value + 80 * 1000) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
now = duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
}
解决此问题的正确方法是什么?我无法更改data_holder->getTimestamp()
数据类型,必须是uint64_t
因为其他代码也在使用它。
这是错误:
error: cannot convert std::chrono::time_point<std::chrono::_V2::system_clock, std::chrono::duration<long int, std::ratio<1l, 1000000000l> > >â to âuint64_t {aka long unsigned int}â in initialization
更新:
Solution A
如果下面的一切看起来都很好,我可以像这样使用而不是使用吗?
解决方案 B:
uint64_t now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
bool is_old = (120 * 1000 < (now - data_holder->getTimestamp()));