View Single Post
Codemonkey's Avatar Codemonkey Codemonkey is offline Super Moderator 2006-11-05 #8 Old  
007 - Measuring frames per second
Last edited by Codemonkey : 2006-11-07 at 12:11.
 
A lot of the time while debugging/profiling, you'll be interested in how many FPS your movie is actually pulling to see if there's something slowing it down.

Here's a class that let's you specify the update interval and invokes a method each time. You can drop this class in a util folder and use it in any of your projects:

ActionScript Code:
  1. import mx.utils.Delegate;
  2.  
  3. class util.FPS {
  4.     private static var instance:FPS;
  5.     private var time:Number;
  6.     private var counter:Number;
  7.     private var interval:Number;
  8.     private var dummy:MovieClip;
  9.    
  10.     public var onUpdate:Function;
  11.    
  12.     public function FPS(interval:Number) {
  13.         var d:Number = _root.getNextHighestDepth();
  14.         this.dummy = _root.createEmptyMovieClip("fpsmc" + d, d);
  15.         this.interval = interval;
  16.         this.start();
  17.     }
  18.  
  19.     // reset and start measuring
  20.     public function start() {
  21.         counter = 0;
  22.         time = getTimer();
  23.         dummy.onEnterFrame = Delegate.create(this, measure);
  24.     }
  25.  
  26.     public function stop() {
  27.         dummy.onEnterFrame = null;
  28.         delete dummy.onEnterFrame;
  29.     }
  30.  
  31.     // checks whether it should perform a measurement
  32.     private function measure() {
  33.         var now:Number = getTimer();
  34.         var lapsed:Number = now - time;
  35.         if (lapsed >= interval) {
  36.             onUpdate(counter * (1000 / lapsed));
  37.             time = now;
  38.             counter = 0;
  39.         } 
  40.         counter++;
  41.     }
  42. }

To use it:

ActionScript Code:
  1. import util.FPS;
  2.  
  3. // create FPS meter and update every 500ms
  4. var fps:FPS = new FPS(500);
  5. fps.onUpdate = function(fps:Number) {
  6.     trace(fps);
  7. }
Don't set the interval too low though (min. 250ms) or the measurements become unreliable.