Skip to content

Instantly share code, notes, and snippets.

@caridy
Last active December 11, 2015 18:38
Show Gist options
  • Select an option

  • Save caridy/4642875 to your computer and use it in GitHub Desktop.

Select an option

Save caridy/4642875 to your computer and use it in GitHub Desktop.
Boilerplate to write benchmarks and benchtables in NodeJS.
/*jslint node:true, nomen:true, stupid: true */
'use strict';
var Benchmark = require('benchmark').Benchmark,
Benchtable = require('benchtable');
function getSuite(testName) {
var suite;
// enabling benchmark suite
suite = Benchmark.Suite(testName);
suite.on('start', function () {
console.log('Starting benchmarks.');
});
suite.on('cycle', function (event) {
if (!event.target.error) {
console.log(String(event.target));
}
});
suite.on('error', function (event) {
console.error(String(event.target) + String(event.target.error));
});
suite.on('complete', function (event) {
console.warn('Fastest is ' + this.filter('fastest').pluck('name'));
});
return suite;
}
function getSuiteTable(testName) {
var suiteTable;
// enabling benchtable suite
suiteTable = new Benchtable(testName);
suiteTable.on('start', function () {
console.log('Starting benchmarks.');
});
suiteTable.on('cycle', function (event) {
if (!event.target.error) {
console.log(String(event.target));
}
});
suiteTable.on('error', function (event) {
console.error(String(event.target) + String(event.target.error));
});
suiteTable.on('complete', function (event) {
console.warn('Fastest is ' + this.filter('fastest').pluck('name'));
console.log(this.table.toString());
});
return suiteTable;
}
// example of a benchmark test
getSuite('suite one')
// add cases
.add('concat', function () {
var b = 'foo' + 'bar';
})
.add('array join', function () {
var b = ['foo', 'bar'].join('');
})
// spin it
.run();
// example of a benchtable test
getSuiteTable('suite two')
// add functions
.addFunction('RegExp#test', function(s) {
/o/.test(s);
})
.addFunction('String#indexOf', function(s) {
s.indexOf('o') > -1;
})
// add inputs
.addInput('Short string', ['Hello world!'])
.addInput('Long string', ['This is a very big string, isnt it? It is. Really. So, hello world!'])
.addInput('Very long string', ['This is a ' + new Array(200).join("very ") + 'big string, isnt it? It is. Really. So, hello world!'])
.addInput('Extremely long string', ['This is a ' + new Array(20000).join("very ") + 'big string, isnt it? It is. Really. So, hello world!'])
// spin it!
.run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment