Skip to content

Instantly share code, notes, and snippets.

@equalent
Created August 9, 2019 01:14
Show Gist options
  • Select an option

  • Save equalent/809e81c31243e3d92be6ea551c241fbd to your computer and use it in GitHub Desktop.

Select an option

Save equalent/809e81c31243e3d92be6ea551c241fbd to your computer and use it in GitHub Desktop.
Limit framerate at 5 Hz (200 ms)
// source: https://web.archive.org/web/20190809011021/https://stackoverflow.com/questions/38730273/how-to-limit-fps-in-a-loop-with-c
// cody by HolyBlackCat
#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());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment