如果我睡了10毫秒。我需要增加什么来得到一秒?

时间:2017-12-24 20:58:06

标签: c++ chrono

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

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

即。 float x = 0;

每个步骤

x += 0.01

我尝试过0.1,0.01,0.001,但它们看起来都太快或太慢了。

2 个答案:

答案 0 :(得分:4)

我建议使用绝对时间点和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';
}

答案 1 :(得分:0)

一秒钟内有多少10 ms的句号。

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

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