Benchmark.jsの実装例
備忘録代わりに
実行環境
- Node.js 11.5.0
- benchmark 2.1.4
コード
callback関数に関するベンチマークはdeferを利用すれば良い
const fs = require('fs');
const Benchmark = require('benchmark');
const suite = new Benchmark.Suite;
suite
.add('readFileSync', {
fn: () => {
fs.readFileSync('./testfile.txt', { encoding: 'utf8' });
}
})
.add('readFile', {
defer: true,
fn: (deferred) => {
fs.readFile('./testfile.txt', { encoding: 'utf8' }, (error, data) => {
deferred.resolve();
});
}
})
.on('cycle', (event) => {
console.log(String(event.target));
})
.on('complete', () => {
console.log('Fastest is ' + suite.filter('fastest').map('name'));
})
.run({ async: true });
実行結果
readFileSync x 38,949 ops/sec ±3.99% (80 runs sampled)
readFile x 9,808 ops/sec ±3.82% (74 runs sampled)
Fastest is readFileSync