【问题标题】:If I sleep for 10 milliseconds. what do I need to increment by to get a second?如果我睡 10 毫秒。我需要增加什么才能获得一秒钟?
【发布时间】:2017-12-24 20:58:06
【问题描述】:

即我在程序循环中使用std::this_thread::sleep_for(std::chrono::milliseconds(10));

如果我有一个变量在此循环中递增以显示经过的秒数,我需要递增什么?

float x = 0;

每一步:

x += 0.01

我尝试过 0.1、0.01、0.001,但它们似乎都太快或太慢。

【问题讨论】:

  • std::this_thread::sleep_for(std::chrono::milliseconds(10)); 可能不准确。您可能应该改用这种方法(示例中的一种):en.cppreference.com/w/cpp/thread/sleep_for
  • 我建议使用sleep_until 并使用绝对时间点。这样可以避免漂移。
  • 您需要获取经过的睡眠时间的实际持续时间:在进入睡眠之前保存开始时间(例如通过调用chrono::high_resolution_clock::now()),然后在睡眠后保存结束时间最后减去这些值。然后你可以将此持续时间转换为毫秒或秒或其他任何值。
  • 您需要增加 10/1000 或 1/100 或 .01
  • seconds{1} - milliseconds{10} 但是 Galik 关于sleep_until 的评论是最好的建议。

标签: c++ chrono


【解决方案1】:

我建议使用绝对时间点和wait_until()。像这样的:

// steady_clock is more reliable than high_resolution_clock
auto const start_time = std::chrono::steady_clock::now();
auto const wait_time = std::chrono::milliseconds{10};
auto next_time = start_time + wait_time; // regularly updated time point

for(;;)
{
    // wait for next absolute time point
    std::this_thread::sleep_until(next_time);
    next_time += wait_time; // increment absolute time

    // Use milliseconds to get to seconds to avoid
    // rounding to the nearest second
    auto const total_time = std::chrono::steady_clock::now() - start_time;
    auto const total_millisecs = double(std::chrono::duration_cast<std::chrono::milliseconds>(total_time).count());
    auto const total_seconds = total_millisecs / 1000.0;

    std::cout << "seconds: " << total_seconds << '\n';
}

【讨论】:

    【解决方案2】:

    一秒中有多少个 10 毫秒的周期。

      1 sec / 10 ms == 1000 ms / 10 ms == 100  (10 ms periods per second) 
    

    但另请参阅:https://stackoverflow.com/a/37445086/2785528

    【讨论】:

      猜你喜欢
      • 2019-11-02
      • 1970-01-01
      • 2011-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-12
      相关资源
      最近更新 更多