即我在程序循环中使用std::this_thread::sleep_for(std::chrono::milliseconds(10));
。
如果我有一个在这个循环上递增的变量来显示经过的秒数,我需要增加什么?
即yaazkssvpoi
每一步:
float x = 0;
我尝试过0.1,0.01,0.001,但它们看起来都太快或太慢。
我建议使用绝对时间点和x += 0.01
。像这样的东西:
wait_until()
一秒钟内有多少10毫秒的周期。
// 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 sec / 10 ms == 1000 ms / 10 ms == 100 (10 ms periods per second)