Skip to content

Instantly share code, notes, and snippets.

@ayamflow
Created December 8, 2017 00:31
Show Gist options
  • Save ayamflow/375c1f8795ae767cc136e3ac563b9efa to your computer and use it in GitHub Desktop.
Save ayamflow/375c1f8795ae767cc136e3ac563b9efa to your computer and use it in GitHub Desktop.
Performance monitor
// Check FPS estimate over an interval of time and trigger callback if it becomes too slow.
// Ideally callback turn quality settings down (canvas dpr, post process, number of particles, ...)
// See also
// https://mrnmnm.com/
// http://findinglove.activetheory.net
const PAST_FRAMES = 60; // Memorize 1s of render time
const BAD_FRAMES = 30; // Max number of slow frame before downgrade
export default class PerformanceMonitor {
constructor(options = {}) {
this.badFrames = 0;
this.frames = [];
this.downgradeCallback = options.downgradeCallback;
this.fpsThreshold = options.fpsThreshold || 54;
this.lastTime = -1;
}
update(dt) {
this.frames.unshift(dt);
this.frames.length = Math.min(this.frames.length, PAST_FRAMES);
let average = this.frames.reduce(function(reduce, time) {
return reduce + 1/(time/1000);
}, 0) / this.frames.length;
if (average < this.fpsThreshold && this.frames.length >= PAST_FRAMES) {
this.badFrames++;
if (this.badFrames >= BAD_FRAMES) {
this.downgradeCallback();
}
} else {
this.badFrames = Math.max(--this.badFrames, 0);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment