I created an object oriented version of Barış Uşaklı's answer. It also tracks the average fps for the last minute.
Application:
global variable:
var fpsCounter;
Create an object somewhere at the start of your program:
fpsCounter = new FpsCounter();
Call the update method in draw () and update fps-display:
function drawScene() { fpsCounter.update(); document.getElementById('fpsDisplay').innerHTML = fpsCounter.getCountPerSecond(); document.getElementById('fpsMinuteDisplay').innerHTML = fpsCounter.getCountPerMinute();
Note. I just add fps-display updates to the draw function for simplicity. At 60fps, it is set 60 times per second, although once per second is enough.
FpsCounter Code:
function FpsCounter(){ this.count = 0; this.fps = 0; this.prevSecond; this.minuteBuffer = new OverrideRingBuffer(60); } FpsCounter.prototype.update = function(){ if (!this.prevSecond) { this.prevSecond = new Date().getTime(); this.count = 1; } else { var currentTime = new Date().getTime(); var difference = currentTime - this.prevSecond; if (difference > 1000) { this.prevSecond = currentTime; this.fps = this.count; this.minuteBuffer.push(this.count); this.count = 0; } else{ this.count++; } } }; FpsCounter.prototype.getCountPerMinute = function(){ return this.minuteBuffer.getAverage(); }; FpsCounter.prototype.getCountPerSecond = function(){ return this.fps; };
OverrideBuffer Code:
function OverrideRingBuffer(size){ this.size = size; this.head = 0; this.buffer = new Array(); }; OverrideRingBuffer.prototype.push = function(value){ if(this.head >= this.size) this.head -= this.size; this.buffer[this.head] = value; this.head++; }; OverrideRingBuffer.prototype.getAverage = function(){ if(this.buffer.length === 0) return 0; var sum = 0; for(var i = 0; i < this.buffer.length; i++){ sum += this.buffer[i]; } return (sum / this.buffer.length).toFixed(1); };
Heinzlmaen
source share