#include <chrono>
#include <thread>void controlFrameRate(std::chrono::milliseconds frameDuration) {auto startTime = std::chrono::high_resolution_clock::now();// Your drawing/rendering logic hereauto endTime = std::chrono::high_resolution_clock::now();auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime);std::this_thread::sleep_for(frameDuration - elapsedTime);
}int main() {const int framesPerSecond = 30;const std::chrono::milliseconds frameDuration(1000 / framesPerSecond);while (true) {controlFrameRate(frameDuration);}return 0;
}
1秒30帧,1秒等于1000毫秒,所以用1000除以30,得到平均一帧多长时间frameDuration
当处理完一帧图片的时候,得到elapsedTime。如果elapsedTime小于frameDuration,这个时候要让程序暂停一下,即std::this_thread::sleep_for,让进程睡一会,然后再进行下一次的工作;如果elapsedTime大于frameDuration,这样应该达不到1秒30帧的频率
这样就能控制好,是1秒30帧的频率。
全部写在主函数里,是下面的代码逻辑
#include <chrono>
#include <thread>int main() {const int framesPerSecond = 30;const std::chrono::milliseconds frameDuration(1000 / framesPerSecond);while (true) {auto startTime = std::chrono::high_resolution_clock::now();// Your drawing/rendering logic hereauto endTime = std::chrono::high_resolution_clock::now();auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime);std::this_thread::sleep_for(frameDuration - elapsedTime);}return 0;
}