C 通过钩住称为每个帧的函数来计算fps

c++ calculate FPS from hooking a function that is called each frame

本文关键字:函数 fps 计算      更新时间:2023-10-16

好吧,所以我正在制作这个小'程序',并希望能够计算fps。我知道,如果我连接一个称为每个帧的函数,我可能可以计算FPS?

这是一个完全的失败,既然我再次查看了这个代码,我看到我认为这有多么愚蠢:

int FPS = 0;
void myHook()
{
    if(FPS<60) FPS++;
    else FPS = 0;
}

显然,这是一次愚蠢的尝试,尽管不确定为什么我什至从逻辑上认为它可能首先起作用...

但是,是的,是否可以通过挂接一个称为每个帧的函数来计算fps?

我坐下来了,当时正在考虑可能做到这一点的方法,但我只是什么都没有想出的。任何信息或任何内容都会有所帮助,感谢您的阅读:)

这应该做技巧:

int fps = 0;
int lastKnownFps = 0;
void myHook(){ //CALL THIS FUNCTION EVERY TIME A FRAME IS RENDERED
    fps++;
}
void fpsUpdater(){ //CALL THIS FUNCTION EVERY SECOND
    lastKnownFps = fps;
    fps = 0;
}
int getFps(){ //CALL THIS FUNCTION TO GET FPS
    return lastKnownFps;
}

您可以调用挂钩函数进行FPS计算,但在能够做到这一点之前:

  1. 每次执行redraw

  2. 时,通过增加计数器来跟踪帧
  3. 跟踪自上次更新以来已经过去了多少时间(获取钩函数中的当前时间)

  4. 计算以下

    frames / time
    

使用高分辨率计时器。使用合理的更新率(1/4秒或类似)。

您可以找到琥珀框之间的时间差。这段时间的倒数将为您提供帧速率。您需要实现一个finction getTime_ms(),该restion time_ms()返回MS。

中的当前时间
unsigned int prevTime_ms = 0;
unsigned char firstFrame = 1;
int FPS                  = 0;
void myHook()
{
    unsigned int timeDiff_ms = 0;
    unsigned int currTime_ms = getTime_ms(); //Get the current time.
    /* You need at least two frames to find the time difference. */
    if(0 == firstFrame)
    {
        //Find the time difference with respect to previous time.
        if(currTime_ms >= prevTime_ms)
        {
            timeDiff_ms = currTime_ms-prevTime_ms;
        }
        else
        {
            /* Clock wraparound. */
            timeDiff_ms = ((unsigned int) -1) - prevTime_ms;
            timeDiff_ms += (currTime_ms + 1);
        }
        //1 Frame:timeDiff_ms::FPS:1000ms. Find FPS.
        if(0 < timeDiff_ms) //timeDiff_ms should never be zero. But additional check.
            FPS = 1000/timeDiff_ms;
    }
    else
    {
        firstFrame  = 0;
    }
    //Save current time for next calculation.
    prevTime_ms = currTime_ms;
}