I\'m trying to limit the frames per second in a loop that is performing intersection checking, using C++ with chrono and thread.
Here is my code:
std::ch
If you think about how your code works, you'll find out that it works exactly how you wrote it. Delta oscillates because of a logical mistake in the code.
This is what happens:
delta == 0
.200
, you code sleeps 200 - delta(0) == 200
ms.200
(because you've measured that sleep time as well as an actual work) and you sleep 200 - delta(200) == 0
ms.To fix the problem you need to not measure the sleep time.
This is how it can be done:
#include
#include
#include
#include
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 work_time = a - b;
if (work_time.count() < 200.0)
{
std::chrono::duration delta_ms(200.0 - work_time.count());
auto delta_ms_duration = std::chrono::duration_cast(delta_ms);
std::this_thread::sleep_for(std::chrono::milliseconds(delta_ms_duration.count()));
}
b = std::chrono::system_clock::now();
std::chrono::duration sleep_time = b - a;
// Your code here
printf("Time: %f \n", (work_time + sleep_time).count());
}
}
This code gives me a steady sequence of deltas:
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