【问题标题】:Call a block of code once every 10ms in a while loop without stopping the loop c++在while循环中每10ms调用一次代码块而不停止循环c ++
【发布时间】:2022-11-20 23:54:33
【问题描述】:

所以我试图在 while 循环中每 10 毫秒运行一次代码块,而不停止循环(休眠)。

我想实现这样的目标:

while (true) {
    if (should_run_the_10ms_code) {
        // some code (once every 10 ms)
    }

    // some other code (every tick)
}

【问题讨论】:

  • 使用计时器,例如 QTimer。
  • @JesperJuhl 这可以工作,但我不想为如此简单的事情拥有一个完整的库
  • 然后自己实现类似的功能。
  • @JesperJuhl 如果我知道如何或找到一些代码我就不会问这个问题
  • 如果您的程序应该如何表现,例如,由于系统负载高,执行代码块延迟 5 毫秒,以便它仅在 15 毫秒而不是 10 毫秒后执行。那么下一次要等多久才能执行呢?为了“赶上”,它应该只有 5 毫秒而不是 10 毫秒吗?还是应该再次为 10ms?

标签: c++ loops timer


【解决方案1】:

std::chrono::steady_clock::now 为您提供单调时钟的当前时间。这是一个相对简单的使用方法:

auto timer = std::chrono::steady_clock::now();
while (true) {
    auto now = std::chrono::steady_clock::now();
    std::chrono::duration<double, std::milli> timer_diff_ms = timer - now;
    if (timer_diff_ms >= 10.0) {
        // some code (once every 10 ms)
        timer = now;
        // or
        // timer = std::chrono::steady_clock::now();
        // if the "some code" takes a bit of time
    }

    // some other code (every tick)
}

请注意,如果 now() 调用之间发生了长时间的事情(可能在“其他代码”部分,可能与您的程序完全无关),则 timer_diff_ms 可能比 10 大得多。

如果您不需要 double(它将是某种整数类型),您也可以使用 std::chrono::milliseconds 而不是 std::chrono::duration&lt;double, std::milli&gt;。

【讨论】:

  • 非常感谢!自己做这个会很痛苦,因为我没有使用 C++ 定时器的经验
  • 您可以将计时器提前 10 毫秒,而不是 timer = now。这样一来,从长远来看,您可以保证每秒接到 100 次调用
猜你喜欢
  • 2018-03-15
  • 1970-01-01
  • 2015-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-15
  • 1970-01-01
相关资源
最近更新 更多