c++ - 在 C++ 中获取耗时仅几秒钟

标签 c++ 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() 因为我需要捕捉每一帧。我怎样才能做到并行?

最佳答案

从 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 为真)长达整整一秒,这意味着您的"Do something..."部分会错误地执行很多次。

关于c++ - 在 C++ 中获取耗时仅几秒钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53704361/

相关文章:

C++:将当前时间与下一个工作时间进行比较

c++ - 如何格式化 std::chrono 持续时间?

c++ - 使用 C++ 在多线程应用程序中测量全局时间(挂钟)的最快方法

c++ - 在 cout 中进行算术运算时,chrono duration_cast 不起作用

C++ 使用自定义权重 boost prim 的算法?

c# - 在 C++ 函数执行后使用 GCHandle 崩溃将大型结构数组从 C# unity 脚本传递到 C++ dll

c++ - 空终止字符串

c++ - std::chrono time_since_epoch 的默认持续时间

c++ - 使用 Python 和 C++ 进行实时处理和回调

c++ - 数据类型之间的隐式转换