我试图通过查看数据的时间戳来查看我的数据是否有120秒(或2分钟)的旧数据,因此我在C ++中使用chrono包时具有以下代码:

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()));

最佳答案

实际上,我建议您更多地朝解决方案A的方向发展,并将其余的uint64_t时间转换为time_points:chrono单位制非常有用。我将从定义一个辅助函数开始,以将对象上的uint64_t时间戳转换为time_points:

using u64_millis = duration<uint64_t, milli>;
static time_point<system_clock, u64_millis> u64_to_time(uint64_t timestamp) {
    return time_point<system_clock, u64_millis>{u64_millis{timestamp}};
}


如果您的时期与system_clock的时期不同,则可以在此处进行修复。使用milliseconds而不是u64_millis可能也可以工作,但是milliseconds的表示形式没有明确定义,以上述方式进行操作可确保类型正确匹配。

现在,您发布的代码如下所示:

auto now = system_clock::now();
bool is_old = now - u64_to_time(data_holder->getTimestamp()) > minutes{2};

auto value = now;
while (now - u64_to_time(data_holder->getTimestamp()) < seconds{80}
        && now - value < seconds{80}) {
    this_thread::sleep_for(milliseconds{100});
    now = system_clock::now();
}

10-08 09:25
查看更多