我正在尝试使用<进行固定时间步循环。 chrono>。
这是我的代码:
#include <iostream>
#include <chrono>
int main()
{
std::chrono::steady_clock::time_point start;
const double timePerFrame = 1.0 / 60.0;
double accumulator = 0.0;
int i = 0;
while(true)
{
start = std::chrono::steady_clock::now();
while(accumulator >= timePerFrame)
{
accumulator -= timePerFrame;
std::cout << ++i << std::endl;
//update();
}
accumulator += std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::steady_clock::now() - start).count();
//render();
}
return 0;
}
变量“i”的值每秒打印少于60次。当我尝试将“timePerFrame”更改为“1.0”时,会发生同样的情况。这有什么问题?
答案 0 :(得分:2)
#include <iostream>
#include <chrono>
#include <thread>
int main()
{
using namespace std::chrono;
using Framerate = duration<steady_clock::rep, std::ratio<1, 60>>;
auto next = steady_clock::now() + Framerate{1};
int i = 0;
while(true)
{
std::cout << ++i << std::endl;
//update();
std::this_thread::sleep_until(next);
next += Framerate{1};
//render();
}
return 0;
}
忙碌的循环也是如此:
int main()
{
using namespace std::chrono;
using Framerate = duration<steady_clock::rep, std::ratio<1, 60>>;
auto next = steady_clock::now() + Framerate{1};
int i = 0;
while(true)
{
std::cout << ++i << std::endl;
//update();
while (steady_clock::now() < next)
;
next += Framerate{1};
//render();
}
return 0;
}