Quick Tip: How to Build a Frame Rate Counter in ActionScript 3.0

In this Quick Tip you'll learn how to measure the current frame rate of your Flash application using ActionScript 3, and display the FPS on screen.

The Importance of Frame Rate

Frame Rate, or Frames per Second (fps), is the frequency at which an imaging device produces unique consecutive images called frames. The term applies equally well to computer graphics, video cameras, film cameras, and motion capture systems.

Each frame is a still image; displaying frames in quick succession creates the illusion of motion. The more frames per second (fps), the smoother the motion appears.

Measuring the fps will enable you to check the performance of your movie or application and make optimizations if necessary.

This can be very useful when testing an application that will run in different environments, the internet browser, the desktop, television boradcast or a mobile device.

With a little help from ActionScript 3, we'll calculate the frame rate using the getTimer() method and create a TextField to display the results, realtime, in the Stage.

Step 1: Create a New File

Open Flash and create a new Flash File (ActionScript 3).

Step 2: Open Actions Panel

Press Option/Alt + F9, or go to Window > Actions to open the Actions Panel.

Step 4: Main Function

This is the main function of our counter:

function fpsCounter():void
{
startTime = getTimer(); //Gets the time in milliseconds since the movie started
addChild(fps); // Adds the TextField to the stage
addEventListener(Event.ENTER_FRAME, checkFPS); //Adds an EnterFrame listener and executes the checkFPS function
}

Step 5: Check on Enter Frame

This function calculates the fps on enter frame:

function checkFPS(e:Event):void
{
var currentTime:Number = (getTimer() - startTime) / 1000; //Gets the time in seconds since the function is executed
framesNumber++; //Ads one to the frame counter
if (currentTime > 1) //If the time in seconds is greater than 1
{
fps.text = "FPS: " + (Math.floor((framesNumber/currentTime)*10.0)/10.0); //Calculates the frame rate and displays it in the textfield
startTime = getTimer(); //Reset the start time
framesNumber = 0; //Reset the number of frames
}
}