Skip to content

Instantly share code, notes, and snippets.

@zeusdeux
Created April 21, 2023 20:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeusdeux/75e51ee7f6cf5e39cbf6af377de20793 to your computer and use it in GitHub Desktop.
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
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