Created
April 21, 2023 20:15
-
-
Save zeusdeux/75e51ee7f6cf5e39cbf6af377de20793 to your computer and use it in GitHub Desktop.
A function that runs async functions and prints how long they take to stderr with a given string as the prefix message
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
export async function timed<T>( | |
cb: () => Promise<T>, | |
message: string, | |
debug = (...args: any[]) => console.warn(...args), | |
): ReturnType<typeof cb> { | |
const start = performance.now(); | |
const result = await cb(); | |
const end = performance.now(); | |
let timeSpent = end - start; | |
let unit = "ms"; | |
if (timeSpent > 1000) { | |
timeSpent /= 1000; | |
unit = "s"; | |
} | |
// timed operations always print to stderr | |
debug(message, `${timeSpent.toFixed(4)}${unit}`); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment