Skip to content

Instantly share code, notes, and snippets.

@martinwells
Last active August 29, 2015 13:57
Show Gist options
  • Save martinwells/9770471 to your computer and use it in GitHub Desktop.
Save martinwells/9770471 to your computer and use it in GitHub Desktop.
Low impact FPS counter
class FPSCounter extends TextField
{
public var currentFPS (default, null):Float;
private var cacheCount:Int;
private var times:Array <Float>;
private var lastUIUpdate:Float;
public function new(x:Float = 10, y:Float = 10, color:Int = 0x000000, fontSize:Int=24) {
super ();
this.x = x;
this.y = y;
currentFPS = 0;
lastUIUpdate = 0;
selectable = false;
defaultTextFormat = new TextFormat("_sans", fontSize, color, true);
text = "";
cacheCount = 0;
times = [];
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
// Event Handlers
private function onEnterFrame (event:Event):Void {
var currentTime = Timer.stamp ();
times.push(currentTime);
while (times[0] < currentTime - 1) {
times.shift();
}
var currentCount = times.length;
currentFPS = Math.round ((currentCount + cacheCount) / 2);
if (currentCount != cacheCount && visible) {
var sinceLastUpdate = currentTime - lastUIUpdate;
if (sinceLastUpdate > 3)
{
text = "" + currentFPS + " fps";
lastUIUpdate = currentTime;
}
}
cacheCount = currentCount;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment