JavaScriptの処理時間を計測する(console.time / console.timeEnd)

肝心なところ知らないこと多い...。

console.timeconsole.timeEnd で挟んだ部分の時間を計測できる。引数にはラベル名を指定できてそのラベルで対応した範囲の時間が計測される。

// Indexing
console.time("indexing");
var stream = byline(fs.createReadStream('/tmp/foo.txt', { encoding: 'utf8' }));

var i=0;
stream.on('data', function(line) {
  indexing(i, line);
  i++;
});

stream.on('finish', function(){
  console.timeEnd("indexing");

  // Search
  console.time("search");
  var res = search("コロスケ", 2);
  console.timeEnd("search");

  // Results
  var resultOut = _.template("文書番号=<%=no %> : 文字位置=<%=pos %>")

  _.each(res, function(v){
    console.log(resultOut(v));
  });
});

こうすると、以下の様な形で処理時間を計測できる。

$ node test.js

indexing: 5ms
search: 1ms
文書番号=0 : 文字位置=15
文書番号=2 : 文字位置=8
文書番号=2 : 文字位置=35