Skip to content

Instantly share code, notes, and snippets.

@mdjastrzebski
Last active November 6, 2024 12:40
Show Gist options
  • Save mdjastrzebski/0cab618ff6dfb5283cb868533efcc644 to your computer and use it in GitHub Desktop.
Save mdjastrzebski/0cab618ff6dfb5283cb868533efcc644 to your computer and use it in GitHub Desktop.
import { useEffect } from 'react'
export class Timer {
name: string
lastTimestamp = 0
counts = new Map<string, number>()
durations = new Map<string, number>()
totalDuration = 0
totalCount = 0
constructor(name: string) {
this.name = name
}
prepare() {
this.lastTimestamp = performance.now()
this.totalCount += 1
}
slice(name: string) {
const duration = performance.now() - this.lastTimestamp
this.durations.set(name, (this.durations.get(name) ?? 0) + duration)
this.counts.set(name, (this.counts.get(name) ?? 0) + 1)
this.totalDuration += duration
this.lastTimestamp = performance.now()
}
printSummary() {
const sorted = Array.from(this.durations.entries()).sort((a, b) => b[1] - a[1])
console.log('⏱️ Total:', this.name, this.totalDuration, this.totalDuration / this.totalCount, this.totalCount)
for (const [name, duration] of sorted.slice(0, 10)) {
const count = this.counts.get(name) ?? 0
console.log(` - ${name}:`, duration, duration / count, count)
}
}
usePrintSummary() {
// eslint-disable-next-line react-hooks/rules-of-hooks
useEffect(() => {
const id = setTimeout(() => this.printSummary(), 5000)
return () => clearTimeout(id)
}, [])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment