How to do a XNA fps counter

Frame rate or FPS, how it is most commonly known is a way for you to know how many images per second is you game drawing. The more the better. Less then 30 and you start to see hiccups.

So how can you measure your frame rate in XNA?

Inside your game1 class declare these vars:

SpriteFont  _spr_font;
int _total_frames = 0;
float _elapsed_time = 0.0f;
int _fps = 0;

On function LoadContent() do

// Put the name of the font
_spr_font = Content.Load("kootenay"); you have on your project

On the update pump do:

 protected override void Update(GameTime gameTime)
            // Update
            _elapsed_time += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
            // 1 Second has passed
            if (_elapsed_time >= 1000.0f)
                _fps = _total_frames;
                _total_frames = 0;
                _elapsed_time = 0;
            // Allows the game to exit
            if (Keyboard.GetState().IsKeyDown(Keys.Escape))

Finally on Draw function do:

protected override void Draw(GameTime gameTime)
            // Only update total frames when drawing
            spriteBatch.DrawString(_spr_font, string.Format("FPS={0}", _fps),
                new Vector2(10.0f, 20.0f), Color.White);

If everything went alright you should have a white counter on the upper left screen. You probably want to turn this into a drawable component or adjusting it to be an independent component on your engine.


Here’s the project for VC# Express : download

note: For those who have asked me why do I use a prefix _ on some variables. I use this to help me know which vars are members of the class and which aren’t. I don’t like using mPosition, instead I use _Position.

Back to Top