A very simple frames per second function source code

This snippet submitted by Jeff Verkoeyen on 2005-01-20. It has been viewed 37834 times.
Rating of 5.8 with 197 votes

/******
Usage:
Merely call this function once at the
beginning of your game loop and the
frames per second will be calculated.

variables:
fps- should be self-explanatory
g_speed- a variable that you may use as
   as scalar in equations to make
   everything run the same speed
   (the default fps speed is 60,
   therefor if the frames per second
   is 60, g_speed will be 1.0, if the
   frames per second is 120, g_speed
   will be 0.5)

******/
 
 ULONG lastTick=GetTickCount(),currTick=GetTickCount();
ULONG UPDATESPEED;
UINT frames=0;
float fps=60.0f;
float g_speed;

void CalcFPS()
{
	currTick=GetTickCount();
	ULONG tickDiff=currTick-lastTick;
	frames++;
	if(tickDiff>=UPDATESPEED)
	{
		lastTick=currTick;
		float calcVal=1/((float)UPDATESPEED/1000.0f);	// Inverse
		float fpsCalc=(float)frames*calcVal;		// Calculates our frames in one second
		fps+=fpsCalc;
		fps/=2;
		frames=0;
		g_speed=60/fps;
	}
}




More C and C++ source code snippets

Add a snippet!