Skip to content

Instantly share code, notes, and snippets.

@michaeldll
Last active December 13, 2024 11:04
Show Gist options
  • Save michaeldll/0692d609350b00fcdd8932cc3d153da7 to your computer and use it in GitHub Desktop.
Save michaeldll/0692d609350b00fcdd8932cc3d153da7 to your computer and use it in GitHub Desktop.
Gobelins FramerateManager
/**
* @returns Average of an array
*/
export function getAverage(arr) {
let sum = 0;
for (let index = 0; index < arr.length; index++) {
sum = sum + arr[index];
}
const avg = sum / arr.length;
return avg !== Infinity ? avg : 0;
}
/**
* Calculates FPS over time.
* this.count adjusts averaging.
*
* @example:
*
* Top of main.js:
* let now = 0, deltaTime = 0;
* const framerateManager = new FramerateManager();
*
* In main.js > setupPane():
* framerateManager.addMeter(pane)
*
* In main.js > animate():
* const animate = (time) => {
* deltaTime = time - now;
* now = time;
* framerateManager.tick(deltaTime)
*/
export default class FramerateManager {
fps = 1
count = 50;
arrayFPS = [];
averageFPS = 0;
addMeter = (pane) => {
const folder = pane.addFolder({
title: "FPS",
expanded: true,
});
folder.addBinding(this, "averageFPS", {
view: "graph",
readonly: true,
interval: 100,
min: 0,
max: 168,
label: "Average FPS over time"
});
folder.addBinding(this, "fps", {
readonly: true,
view: "graph",
interval: 100,
min: 0,
max: 168,
});
};
tick = (deltaTime) => {
this.fps = (1 / deltaTime) * 1000;
if (this.arrayFPS.length < this.count) {
this.arrayFPS.push(this.fps);
} else {
this.averageFPS = getAverage(this.arrayFPS);
this.arrayFPS = [];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment