gpt4 book ai didi

C++如何进行精确的帧率限制?

转载 作者:太空宇宙 更新时间:2023-11-04 12:29:39 24 4
gpt4 key购买 nike

我正在尝试使用 C++ 创建游戏,我想为 fps 创建限制,但我总是得到比我想要的多或少的 fps。当我查看具有 fps 限制的游戏时,它始终是精确的帧率。尝试使用 Sleep() std::this_thread::sleep_for(sleep_until)。例如 Sleep(0.01-deltaTime) 获得 100 fps 但最终以 +-90fps 结束。当 sleep 不精确时,这些游戏如何如此精确地处理 fps?我知道我可以使用无限循环来检查时间是否过去,但它正在使用 CPU 的全部功能,但我想在没有 VSync 的情况下将 CPU 使用率降低到这个限制。

最佳答案

您可以在开始时记录时间点,为其添加固定持续时间并休眠,直到计算的时间点出现在每个循环的结束(或开始)。示例:

#include <chrono>
#include <iostream>
#include <ratio>
#include <thread>

template<std::intmax_t FPS>
class frame_rater {
public:
frame_rater() : // initialize the object keeping the pace
time_between_frames{1}, // std::ratio<1, FPS> seconds
tp{std::chrono::steady_clock::now()}
{}

void sleep() {
// add to time point
tp += time_between_frames;

// and sleep until that time point
std::this_thread::sleep_until(tp);
}

private:
// a duration with a length of 1/FPS seconds
std::chrono::duration<double, std::ratio<1, FPS>> time_between_frames;

// the time point we'll add to in every loop
std::chrono::time_point<std::chrono::steady_clock, decltype(time_between_frames)> tp;
};

// this should print ~10 times per second pretty accurately
int main() {
frame_rater<10> fr; // 10 FPS
while(true) {
std::cout << "Hello world\n";
fr.sleep(); // let it sleep any time remaining
}
}

关于C++如何进行精确的帧率限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59165392/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com