Reputation: 343
Ok, so i am making this little 'program' and would like to be able to calculate FPS. I had an idea that if i hook a function that is called each frame i could possibly calculate the FPS?
Here's a complete fail, now that i look at it this code again i see how stupid i was to think this would work:
int FPS = 0;
void myHook()
{
if(FPS<60) FPS++;
else FPS = 0;
}
Obviously this is an idiotic attempt, though not sure why i even logically thought it might work in the first place...
But yeah, IS it possible to calculate FPS via hooking a function that is called each frame?
I sat down and was thinking of possible ways to do this but i just couldn't come up with anything. Any info or anything would be helpful, thanks for reading :)
Upvotes: 0
Views: 716
Reputation: 1947
You can find the time difference between succussive frames. The inverse of this time will give you frame rate. You need to implement a finction getTime_ms() which returns current time in 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;
}
Upvotes: 1
Reputation: 43662
You can call your hook function to do the fps calculation but before being able to do that you should:
Keep track of the frames by incrementing a counter each time a redraw is performed
Keep track of how much time has passed since last update (get the current time in your hook function)
Calculate the following
frames / time
Use a high resolution timer. Use a reasonable update rate (1/4 sec or the like).
Upvotes: 1
Reputation: 589
This should do the trick:
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;
}
Upvotes: 1