在 C++ 中经过 30 毫秒后退出循环的最佳方法是什么

2021-12-31 00:00:00 timer qt c++ clock

在 C++ 中退出循环的最佳方法是尽可能接近 30 毫秒.轮询提升:microsec_clock ?轮询 QTime ?还有什么?

What is the best way to exit out of a loop as close to 30ms as possible in C++. Polling boost:microsec_clock ? Polling QTime ? Something else?

类似于:

A = now;
for (blah; blah; blah) {
    Blah();
    if (now - A > 30000)
         break;
}

它应该适用于 Linux、OS X 和 Windows.

It should work on Linux, OS X, and Windows.

循环中的计算用于更新模拟.每 30 毫秒,我想更新一次视口.

The calculations in the loop are for updating a simulation. Every 30ms, I'd like to update the viewport.

推荐答案

此链接中的代码片段示例几乎可以满足您的需求:

The code snippet example in this link pretty much does what you want:

http://www.cplusplus.com/reference/clibrary/ctime/时钟/

改编自他们的例子:

void runwait ( int seconds )
{
   clock_t endwait;
   endwait = clock () + seconds * CLOCKS_PER_SEC ;
   while (clock() < endwait)
   {
      /* Do stuff while waiting */
   }
}

相关文章