问题
i.e. i'm using std::this_thread::sleep_for(std::chrono::milliseconds(10));
in a program loop.
If I have a variable that gets incremented on this loop to show seconds elapsed, what do I need to increment by?
i.e. float x = 0;
for each step:
x += 0.01
I've tried 0.1, 0.01, 0.001, but they all seem either too fast or too slow.
回答1:
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';
}
回答2:
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
来源:https://stackoverflow.com/questions/47963973/if-i-sleep-for-10-milliseconds-what-do-i-need-to-increment-by-to-get-a-second