If I sleep for 10 milliseconds. what do I need to increment by to get a second?

青春壹個敷衍的年華 提交于 2019-12-01 01:54:51

I would recommend using absolute time points and wait_until(). Something like this:

// 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';
}

how many 10 ms periods in one second.

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

But see also: https://stackoverflow.com/a/37445086/2785528

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!