std::chrono - 固定时间步长循环
std::chrono - fixed time step loop
我正在尝试使用<时间>进行固定的时间步长循环。时间>
这是我的代码:
#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"时,也会发生同样的情况。它有什么问题?
#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;
}
相关文章:
- while循环中while循环的时间复杂度是多少
- 在基于范围的for循环中使用结构化绑定声明
- 我可以创建一个包含两个变量的 for 循环,但时间复杂度仍然为 O(n) 吗?
- 具有嵌套 if-else 的循环的时间复杂度
- 在做一段时间内检查字符的无限循环
- 整个循环花费的时间比其迭代总和要长
- 如何在 for 循环中的特定时间内获取要打印的额外值
- 为什么切换 for 循环的顺序会显著改变执行时间?
- 是否有可能实现O(N)时间和O(1)空间解决方案,以实现C++中的字符串循环移位
- 2 个嵌套循环的时间复杂度
- 带有 if 语句的嵌套循环的时间复杂度
- 带有多个内部回路的循环的时间复杂性
- C++ 数组循环的时间复杂度
- Qt在游戏循环中短时间内停止关键事件
- 模板变量的绑定时间
- 以下循环的时间复杂度是多少
- 内部 for 循环的时间复杂度
- 嵌套循环的时间复杂度:cn(n+1)/2从何而来
- 有条件的大平面数组遍历和令人惊讶的短循环执行时间
- 为什么循环执行时间的此C++存在显着差异?