Skip to content

Instantly share code, notes, and snippets.

@bericp1
Created July 19, 2019 22:57
Show Gist options
  • Save bericp1/38753159d8d98bfe80370f085f845f1e to your computer and use it in GitHub Desktop.
Save bericp1/38753159d8d98bfe80370f085f845f1e to your computer and use it in GitHub Desktop.
Creates a high resolution timer. Call with a name to start. Call with a new name to "lap". Call with no arguments to stop.
function createTimer (log) {
let prev = null;
function hrtimeDurationToMs([durS, durUs]) {
return ((durS * 1000) + (durUs / 1000000)).toFixed(4);
}
return (name = null) => {
if (prev) {
const dur = hrtimeDurationToMs(process.hrtime(prev[1]));
log(`end ${prev[0]}, took ${dur}ms`, { name: prev[0], hrtime: prev[1], dur });
}
if (name) {
const hrtime = process.hrtime();
prev = [name, hrtime];
log(`start ${name}`, { name, hrtime });
} else {
prev = null;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment