我试图使用带有 chrono 和 thread 的 C++ 来限制执行相交检查的循环中的每秒帧数。
这是我的代码:
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
std::chrono::system_clock::time_point lastFrame = std::chrono::system_clock::now();
while (true)
{
// Maintain designated frequency of 5 Hz (200 ms per frame)
now = std::chrono::system_clock::now();
std::chrono::duration<double, std::milli> delta = now - lastFrame;
lastFrame = now;
if (delta.count() < 200.0)
{
std::chrono::duration<double, std::milli> delta_ms(200.0 - delta.count());
auto delta_ms_duration = std::chrono::duration_cast<std::chrono::milliseconds>(delta_ms);
std::this_thread::sleep_for(std::chrono::milliseconds(delta_ms_duration.count()));
}
printf("Time: %f \n", delta.count());
// Perform intersection test
}
我遇到的问题是 delta 的所有其他输出都显示出很小的量,而不是我想要的大约 200 毫秒/帧:
Time: 199.253200
Time: 2.067700
Time: 199.420400
Time: 2.408100
Time: 199.494200
Time: 2.306200
Time: 199.586800
Time: 2.253400
Time: 199.864000
Time: 2.156500
Time: 199.293800
Time: 2.075500
Time: 201.787500
Time: 4.426600
Time: 197.304100
Time: 4.530500
Time: 198.457200
Time: 3.482000
Time: 198.365300
Time: 3.415400
Time: 198.467400
Time: 3.595000
Time: 199.730100
Time: 3.373400
对于为什么会发生这种情况有什么想法吗?
如果您考虑一下您的代码是如何工作的,您会发现它完全按照您编写的方式工作。由于代码中的逻辑错误,Delta 发生振荡。
发生的情况是这样的:
- 我们从
delta == 0
.
- 因为 Delta 小于
200
,你的代码睡觉了200 - delta(0) == 200
ms.
- 现在,三角洲本身已经接近
200
(因为您已经测量了睡眠时间以及实际工作时间)并且您睡觉了200 - delta(200) == 0
ms.
- 之后,循环重复。
要解决这个问题,您不需要测量睡眠时间。
可以这样做:
#include <iostream>
#include <cstdio>
#include <chrono>
#include <thread>
std::chrono::system_clock::time_point a = std::chrono::system_clock::now();
std::chrono::system_clock::time_point b = std::chrono::system_clock::now();
int main()
{
while (true)
{
// Maintain designated frequency of 5 Hz (200 ms per frame)
a = std::chrono::system_clock::now();
std::chrono::duration<double, std::milli> work_time = a - b;
if (work_time.count() < 200.0)
{
std::chrono::duration<double, std::milli> delta_ms(200.0 - work_time.count());
auto delta_ms_duration = std::chrono::duration_cast<std::chrono::milliseconds>(delta_ms);
std::this_thread::sleep_for(std::chrono::milliseconds(delta_ms_duration.count()));
}
b = std::chrono::system_clock::now();
std::chrono::duration<double, std::milli> sleep_time = b - a;
// Your code here
printf("Time: %f \n", (work_time + sleep_time).count());
}
}
这段代码给了我一个稳定的增量序列:
Time: 199.057206
Time: 199.053581
Time: 199.064718
Time: 199.053515
Time: 199.053307
Time: 199.053415
Time: 199.053164
Time: 199.053511
Time: 199.053280
Time: 199.053283
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)