Skip to content

Instantly share code, notes, and snippets.

@jonschlinkert
Last active February 8, 2024 08:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonschlinkert/c8eb2a41ca4bea7d1ae2123363a639bf to your computer and use it in GitHub Desktop.
Save jonschlinkert/c8eb2a41ca4bea7d1ae2123363a639bf to your computer and use it in GitHub Desktop.
Minimal code to create a benchmarks with terminal styling to show real-time progress while benchmarks are running.
const { Suite } = require('benchmark');
const argv = require('minimist')(process.argv.slice(2));
const cycle = (e, newline) => {
process.stdout.write('\u001b[G');
process.stdout.write(` ${e.target}` + (newline ? '\n' : ''));
};
function bench(name) {
const suite = new Suite()
.on('start', () => console.log(`# ${name}`))
.on('complete', function() {
const fastest = this.filter('fastest').map('name').toString();
console.log(`Fastest is '${fastest}'`);
console.log();
});
const ste = {
run: suite.run.bind(suite),
add(key, fn) {
suite.add(key, {
onCycle: e => cycle(e),
onComplete: e => cycle(e, true),
onError(err) {
console.error(err);
process.exit(1);
},
fn
});
return ste;
}
};
return ste;
}
/**
* Example usage
*/
bench('some-comparisons')
.add('one', () => {
// do stuff
})
.add('two', () => {
// do stuff
})
.add('three', () => {
// do stuff
})
.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment