C++ C++;如何正确限制FPS(使用GLFW)

C++ C++;如何正确限制FPS(使用GLFW),c++,sleep,glfw,frame-rate,C++,Sleep,Glfw,Frame Rate,因此,我一直试图将fps限制在60: //Those are members inside the Display class double tracker = glfwGetTime(); const float frameCap = 1 / 60.0f; void Display::present() { glfwSwapBuffers( _window ); //Getting the time between each call double now = g

因此,我一直试图将fps限制在60:


//Those are members inside the Display class
double tracker = glfwGetTime();
const float frameCap = 1 / 60.0f;

void Display::present() {
    glfwSwapBuffers( _window );

    //Getting the time between each call
    double now = glfwGetTime( );
    double frameTime=now - tracker;
    tracker=now;
    
    //delaying if required
    if ( frameTime < frameCap )
        delay( frameCap - frameTime );
}

我的延迟/睡眠功能

#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif

void delay( uint32_t ms )
{
#ifdef _WIN32
    Sleep( ms );
#else
    usleep( ms * 1000 );
#endif
}

\ifdef\u WIN32
#包括
#否则
#包括
#恩迪夫
无效延迟(uint32_t ms)
{
#ifdef_WIN32
睡眠(ms);
#否则
usleep(ms*1000);
#恩迪夫
}
基本上是在每个Display::present()调用中限制帧率的想法


看起来什么都没有被限制事实上第一次调用
present
your
double frameTime=glfwGetTime()-tracker的fps是4000+

,将
frameTime
设置为当前时间(
glfwGetTime()
和使用
glfwGetTime()
设置的
tracker
的初始值之间的差值

在下一行中,您设置了
tracker=frameTime;
frameTime
不是时间,而是这里的差异。)

对于下一次调用
present
,值
tracker
非常小(因为它是差异而不是时间),因为您的
double frameTime=glfwGetTime()-tracker;
变得非常大(大于
frameCap
),所以不会发生睡眠

对于
present
的下一次调用,
(frameTime
的条件可能再次为真,但对于向上的流,它肯定不再为真

因此,至少每隔一秒钟调用
present
时,
delay
将不会被调用


除此之外,
glfGetTime
返回秒,
frameCap
还表示一帧应该持续的秒数,但是您的
void delay(uint32_t ms)
需要毫秒。

您可能不想“睡眠”不管怎么说,只针对帧速率。这可能会导致您错过输入消息,或者如果您的程序运行缓慢,则运行速度会低于60fps。阅读这篇博文可能有助于了解更多信息。这篇博文是针对游戏开发的,但同样的原则适用于这里更新/绘制循环更改答案的方式会使已经给出的答案成为部分ally错了(或完全错了),因为你删除了答案中针对的问题,这是一个非常坏的习惯,绝对不能这样做。这是一个问答平台,而不是论坛。
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif

void delay( uint32_t ms )
{
#ifdef _WIN32
    Sleep( ms );
#else
    usleep( ms * 1000 );
#endif
}