在C ++中获得耗时仅几秒钟

时间:2018-12-10 11:06:49

标签: c++ chrono

我需要获取一段时间的时间。

something.start()
auto start = std::chrono::steadyt_clock::now();
while(something->is_valid())
{
    // getting frames
    auto end = std::chrono::steady_clock::now();
    auto diff = end - start;
    // do something with the frames
    if(diff % 3 == 0) { /* do something with the something */ }

}

但是它得到的时间是每毫秒,我得到的时间和我的if语句运行过多。我不能使用std :: this_thread :: sleep_for(),因为我需要捕捉每一帧。我该怎么办?

1 个答案:

答案 0 :(得分:4)

自C ++ 14起,您可以进行diff >= 3s来查看差异是否等于或大于三秒(请参见this duration literal reference)。

否则,如果您坚持使用C ++ 11,请使用diff >= std::chrono::seconds(3)

请注意,这要求您在每次条件为真时重置start

if (diff >= 3s)
{
    start = end;
    // Do something with the something...
}

这是必需的,因为差异可以保持等于3(因此diff % 3s == 0为真)长达一秒钟,这意味着您的“做某事...”部分将执行许多操作错误的时间。

相关问题