GameComponents: a simple FPS counter

A component you'll probably need sooner or later is a "Frame per Second" counter to have a quantifiable performance index of your game. There are many different ways to implement a frame counter. One of the easiest ones, since XNA provides us the exact time elapsed between the current Draw() call and the previous one, is to simply divide 1 second by the amount of time elapsed in seconds.

int fps = (int)Math.Round(1.0, gameTime.ElapsedRealTime.TotalSeconds);

To find out the exact amount of time (in ms) needed to draw the scene, you can further divide 1 second (1000 ms) by the number of frames per second you are rendering currently:

float frameTime = 1000.0f / fps;

If you render these values, you'll notice that your FPS counter will stay blocked on 60 frames per second (or similar). This is because XNA enables VSync by default: the game is rendered at the exact refresh rate of your monitor and presented once at every refresh, preventing graphic artifacts. To disable VSync, you'll have to paste this code in your Initialize() method:

#if DEBUG IsFixedTimeStep = false; graphics.SynchronizeWithVerticalRetrace = false; graphics.ApplyChanges(); #endif

The #if preprocessor stuff will leave VSync enabled when compiling the release version of your game. IsFixedTimeStep will force XNA to call the Draw() method as frequently as possible, instead of idling when no more frames are technically needed. This will also call your Update() methods more frequently than usual.

Ok, now the FPS counter returns the correct measure. Unfortunately the value tends to vary quickly and if your framerate fluctuates you won't be able to read the counter very easily. To fix this you can use a simple counter to accumulate the values from a fixed amount of frames and then update the averaged fps value.

The code

Download the FPS counter component source code (.zip).