Skip to content

Instantly share code, notes, and snippets.

@ehaynes99
Created October 31, 2022 14:10
Show Gist options
  • Save ehaynes99/f46d685547fe744dca91c9a25567df04 to your computer and use it in GitHub Desktop.
Save ehaynes99/f46d685547fe744dca91c9a25567df04 to your computer and use it in GitHub Desktop.
import { performance } from 'perf_hooks'
export type Timer = ReturnType<typeof createTimer>
/**
* High resolution timer. Note that Number.MAX_SAFE_INTEGER
* limits the total duration to ~104 hours.
*/
export const createTimer = () => {
const times: number[] = []
let startTime = performance.now()
let running = false
const currentElapsed = () => {
if (!running) {
return 0
}
return performance.now() - startTime
}
const timer = {
start: () => {
if (!running) {
startTime = performance.now()
running = true
}
},
stop: () => {
if (running) {
times.push(currentElapsed())
running = false
}
},
timeElapsed: () => {
return times.reduce(
(result, duration) => result + duration,
currentElapsed(),
)
},
timeElapsedFormatted: () => {
format(timer.timeElapsed())
},
}
return timer
}
const format = (duration: number) => {
const extract = (unitLength: number) => {
const value = duration % unitLength
duration = Math.floor(duration / unitLength)
return value
}
const milliseconds = extract(1000)
const seconds = extract(60) + milliseconds / 1000
const minutes = extract(60)
const hours = extract(60)
const strings: string[] = []
if (hours) {
strings.push(`${hours}h`)
}
if (minutes) {
strings.push(`${minutes}m`)
}
const secondsValue = milliseconds ? seconds : seconds.toFixed(1)
strings.push(`${secondsValue}s`)
return strings.join(' ')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment