即我正在使用std :: this_thread :: sleep_for(std :: chrono :: milliseconds(10));在程序循环中.
如果我有一个在这个循环上递增的变量来显示经过的秒数,我需要增加什么?
即浮点x = 0;
每一步:
x += 0.01
我尝试过0.1,0.01,0.001,但它们看起来都太快或太慢.
解决方法:
我建议使用绝对时间点和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';
}