2016-11-26 123 views
0

好的,所以我正在制作这个小程序,并希望能够计算出FPS。我有一个想法,如果我钩一个被称为每帧的函数,我可能会计算出FPS?C++通过挂钩被称为每帧的函数来计算FPS

这里有一个完整的失败,现在,我看它的代码,我再次看到我是多么愚蠢到认为这会工作:

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

显然,这是一个愚蠢的尝试,但不知道为什么我甚至逻辑上认为它可能工作在第一个地方...

但是,是有可能计算FPS通过挂钩被称为每帧的功能?

我坐下来,想着可能的方式来做到这一点,但我只是不能拿出任何东西。任何信息或任何将是有益的,感谢您的阅读:)

+4

测量时间可能有帮助吗? –

回答

1

你可以打电话给你的钩子函数做FPS计算,但能够做之前,你应该:

  1. 跟踪帧通过重绘进行

  2. 多少时间自上次更新已经通过跟踪每次递增计数器(让你的钩子函数当前时间)

  3. 计算下列

    frames/time 
    

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

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

你可以找到succussive帧之间的时间差。这次的倒数会给你帧速率。你需要实现一个函数getTime_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; 

}