Skip to content

Instantly share code, notes, and snippets.

@ranaroussi
Last active August 5, 2022 17:26
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 ranaroussi/d199e27ca791f09a50656410c11ca7ee to your computer and use it in GitHub Desktop.
Save ranaroussi/d199e27ca791f09a50656410c11ca7ee to your computer and use it in GitHub Desktop.
Node timer with nano-second precision
const Timer = require('./timer')
const timer = new Timer();
// do stuff...
timer.stop();
// '1s, 589.334334 ms'
class Timer {
constructor() {
this.start();
this.stoppedAt = null;
this.totalNanoSeconds = 0;
}
start() {
this.absStartedAt = process.hrtime();
this.startedAt = process.hrtime();
}
stop() {
this.stoppedAt = process.hrtime(this.startedAt);
return this.format(this.stoppedAt);
}
lap() {
this.stoppedAt = process.hrtime(this.startedAt);
this.startedAt = process.hrtime();
return this.format(this.stoppedAt);
}
total() {
return this.format(process.hrtime(this.absStartedAt));
}
format(t, decimals = 8) {
t = t || this.stoppedAt;
const ret = [];
if (this.stoppedAt[0] > 0) {
ret.push(`${this.stoppedAt[0]}s`);
}
const ms = this.stoppedAt[1] / 1e6;
if (ms > 1) {
ret.push(`${parseFloat(ms.toFixed(decimals))} ms`);
} else if (ms > 0.1) {
ret.push(`${parseFloat((ms * 100).toFixed(decimals))} μs`);
} else if (ms > 0.01) {
ret.push(`${parseFloat((ms * 1e6).toFixed(decimals))} ns`);
}
return ret.join(', ');
}
}
module.exports = Timer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment