Skip to content

Instantly share code, notes, and snippets.

@ds300
Created April 16, 2024 08:46
Show Gist options
  • Save ds300/63548a67661a732f87062c95d378a9e8 to your computer and use it in GitHub Desktop.
Save ds300/63548a67661a732f87062c95d378a9e8 to your computer and use it in GitHub Desktop.
class Stats {
periods = 0
totals = {} as Record<string, number>
starts = {} as Record<string, number>
start(name: string) {
this.starts[name] = performance.now()
}
end(name: string) {
if (!this.starts[name]) throw new Error(`No start for ${name}`)
this.totals[name] = (this.totals[name] ?? 0) + (performance.now() - this.starts[name])
delete this.starts[name]
}
tick() {
this.periods++
if (this.periods === 60) {
console.log('Stats:')
for (const [name, total] of Object.entries(this.totals).sort((a, b) =>
a[0].localeCompare(b[0])
)) {
console.log(' ', name, total / this.periods)
}
this.totals = {}
this.starts = {}
this.periods = 0
}
}
}
// const stats = new Stats()
// stats.start('blah')
// stats.end('blah')
// stats.tick()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment