Skip to content

Instantly share code, notes, and snippets.

@jeffschwartz
Last active October 1, 2023 12:50
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 jeffschwartz/b1bf17fbce645a5c1c05a45ac9eb5a90 to your computer and use it in GitHub Desktop.
Save jeffschwartz/b1bf17fbce645a5c1c05a45ac9eb5a90 to your computer and use it in GitHub Desktop.
metrics.js uses Node's process.hrtime(time) for nano second precision. Public api: startTimer, stopTimer, forEachTimer, clearTimers.
/**
* Metrics uses process.hrtime(time) for nano second precision.
* public api: startTimer, stopTimer, forEachTimer, clearTimers, filterTimer
*/
import chalk from "chalk";
const timers = new Map();
const startTimer = (name, precision = 3) => {
const timer = {
name,
precision,
started: process.hrtime(),
};
timers.set(name, timer);
};
const noSuchTimer = name => {
console.log(chalk.red(`no such timer named '${name}'`));
};
const stopTimer = name => {
const timer = timers.get(name);
if (!timer) return noSuchTimer(name);
const mills = process.hrtime(timer.started)[1] / 1000000;
timer.elapsed = process.hrtime(timer.started)[0] + " s, " + mills.toFixed(timer.precision) + " ms";
return timer.elapsed;
};
const forEachTimer = callbackFn => timers.size > 0 && timers.forEach(callbackFn);
const filterTimer = (name, callbackFn) => timers.size > 0 && timers.has(name) && callbackFn(timers.get(name));
const clearTimers = () => timers.clear();
export {
startTimer,
stopTimer,
forEachTimer,
filterTimer,
clearTimers,
};
@jeffschwartz
Copy link
Author

jeffschwartz commented Jul 22, 2023

Examples:

metrics.clearTimers();
metrics.startTimer("total elapsed time");
.
.
.
metrics.stopTimer("total elapsed time");
metrics.forEachTimer(timer => console.log(`${timer.name}: ${chalk.green(timer.elapsed)}`));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment