Benchmark.jsでベンチマーク

ずっと前に使ったのだけど、メモもなにもして無くてコードが辛うじて残っていたのでめもめも。

benchmark.jsのインストール

$ npm install benchmark

node.jsだけじゃなく、RingoJSやRhinoでも動作するみたい。jsperfでも使われていたはずなので、当然ブラウザでも動作するはず。

パフォーマンスを計測するコード

index.js
var Benchmark = require('benchmark'),
    suite = new Benchmark.Suite;

var str = 'label:value';

suite
  .add('slice', function() {
    var index = str.indexOf(':');
    str.slice(0, index);
    str.slice(index + 1);
  })
  .add('context', function() {
    str.match(/:/);
    RegExp.leftContext;
    RegExp.rightContext;
  })
  .on('cycle', function(event) {
    console.log(String(event.target));
  })
  .on('complete', function() {
    console.log('Fastest is %s', this.filter('fastest').pluck('name'));
  })
  .run({ async: true });

LTSVの計測でもしてたのかな……

使い方

$ node index.js
slice x 6,661,257 ops/sec ±1.53% (86 runs sampled)
context x 5,504,342 ops/sec ±0.22% (96 runs sampled)
Fastest is slice


これをグラフィカルに表示してくれるようには出来るのかなあ?