Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Last active July 16, 2018 19:11
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 xeoncross/bf47fbfd207cbcfbcfbdc5e04ab2059a to your computer and use it in GitHub Desktop.
Save xeoncross/bf47fbfd207cbcfbcfbdc5e04ab2059a to your computer and use it in GitHub Desktop.
Simple Javascript (node.js and browser) timers for benchmarking and other development testing
// https://nodejs.org/docs/v0.8.0/api/all.html#all_process_hrtime
const timeitnode = function (name) {
const start = process.hrtime();
return {
stop() {
const diff = process.hrtime(start);
console.log('"%s" took %d seconds and %d nanoseconds', name, diff[0], diff[1]);
// return process.hrtime(start);
},
};
};
// https://stackoverflow.com/a/25878121/99923
const timeitbrowser = function (name) {
const start = new Date();
return {
stop() {
const end = new Date();
const time = end.getTime() - start.getTime();
console.log('Timer:', name, 'finished in', time, 'ms');
// return time
},
};
};
// Caculate many runs when you have lots of workers/callbacks and need to time each one
const AverageTimer = () => {
const times = [];
return {
start() {
const start = process.hrtime();
// Closure to allow multiple sub-timers to run
return {
stop() {
times.push(process.hrtime(start));
},
};
},
report(name) {
const seconds = Math.round(times.reduce((a, b) => a + b[0], 0) / times.length);
const nanoseconds = Math.round(times.reduce((a, b) => a + b[1], 0) / times.length);
console.log(
'"%s" took %d seconds and %d microseconds',
name,
seconds,
Math.round(nanoseconds / 1000 / 1000),
);
},
};
};
// Caculate average over many runs and display results in milliseconds
const AverageTimer = () => {
const times = [];
return {
start() {
const start = process.hrtime();
// Closure to allow multiple sub-timers to run
return {
stop() {
times.push(process.hrtime(start));
},
};
},
report(name) {
// Add seconds + nanoseconds
const total = times.reduce((c, n) => c + (n[0] * 1000) + (n[1] / 1000 / 1000), 0);
// Pad string for easy comparison of results
const ms = String(` ${Math.round(total / times.length)}`).slice(-10);
console.log('TIMER: %s ms (average) for "%s"', ms, name);
},
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment