Created
October 31, 2022 14:10
-
-
Save ehaynes99/f46d685547fe744dca91c9a25567df04 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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