Skip to content

Instantly share code, notes, and snippets.

@rynbyjn
Last active December 19, 2019 22:40
Show Gist options
  • Save rynbyjn/624b6bb4b07b177c7ad1cf9cfa1cb39c to your computer and use it in GitHub Desktop.
Save rynbyjn/624b6bb4b07b177c7ad1cf9cfa1cb39c to your computer and use it in GitHub Desktop.
A FPS monitor that tracks averages over last one and five minutes based on [stats.js](https://github.com/mrdoob/stats.js)
// Based on [stats.js](https://github.com/mrdoob/stats.js)
// frames per second (higher is better)
export let fps = 0
// ms to render one frame (lower is better)
export let mspf = 0
// average fps over last minute
export let fpsAvg1Min: number | undefined
// average fps over last 5 minutes
export let fpsAvg5Min: number | undefined
// delta (%) between last two min
export let fpsDelta1Min: number | undefined
// delta (%) between last min and avg of prev 4
export let fpsDelta5Min: number | undefined
let startTime = (performance || Date).now()
let prevTime = startTime
let frames = 0
let fpsArray: number[] = []
const minAvgArray: number[] = []
export const start = () => {
startTime = (performance || Date).now()
}
export const end = () => {
frames++
const time = (performance || Date).now()
mspf = Math.round(time - startTime)
if (time >= prevTime + 1000) {
fps = Math.round((frames * 1000) / (time - prevTime))
console.log('fps', fps)
fpsArray.push(fps)
prevTime = time
frames = 0
calculateAverages()
}
}
const getArrayAverage = arr => arr.reduce((a, b) => a + b) / arr.length
export const calculateAverages = () => {
if (fpsArray.length >= 60) {
fpsAvg1Min = getArrayAverage(fpsArray.slice(0, 60))
minAvgArray.push(fpsAvg1Min)
if (minAvgArray.length >= 2) {
const lastTwoMins = minAvgArray.slice(-2)
fpsDelta1Min = lastTwoMins[1] / lastTwoMins[0]
}
fpsArray = []
if (minAvgArray.length === 5) {
fpsAvg5Min = getArrayAverage(minAvgArray.slice(0, 5))
fpsDelta5Min =
Number(minAvgArray.slice(-1)) / getArrayAverage(minAvgArray.slice(0, 4))
minAvgArray.shift()
}
}
}
// start frame loop (will start running where this file is imported first)
const animate = () => {
start()
// more granular monitored code could go here
end()
requestAnimationFrame(animate)
}
requestAnimationFrame(animate)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment