Last active
February 8, 2024 08:26
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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