【问题标题】:c++ calculate FPS from hooking a function that is called each framec ++通过挂钩每帧调用的函数来计算FPS
【发布时间】:2024-01-06 00:28:01
【问题描述】:

好的,所以我正在制作这个小“程序”并希望能够计算 FPS。我有一个想法,如果我挂钩一个每帧调用的函数,我可能会计算 FPS?

这是一个彻底的失败,现在我再次查看这段代码,我知道我是多么愚蠢地认为这会起作用:

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

显然这是一个愚蠢的尝试,虽然我不知道为什么我什至在逻辑上认为它可能首先会起作用......

但是是的,是否可以通过挂钩每帧调用的函数来计算 FPS?

我坐下来思考可能的方法来做到这一点,但我就是想不出任何办法。任何信息或任何东西都会有帮助,感谢阅读:)

【问题讨论】:

  • 测量时间可能会有所帮助?

标签: c++ hook frame-rate calculation


【解决方案1】:

这应该可以解决问题:

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;
}

【讨论】:

    【解决方案2】:

    您可以调用您的钩子函数来进行 fps 计算,但在能够这样做之前,您应该:

    1. 每次执行重绘时通过递增计数器来跟踪帧

    2. 跟踪自上次更新以来经过了多长时间(在挂钩函数中获取当前时间)

    3. 计算如下

      frames / time
      

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

    【讨论】:

      【解决方案3】:

      您可以找到连续帧之间的时间差。这个时间的倒数将为您提供帧速率。您需要实现一个函数 getTime_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;
      
      }
      

      【讨论】: