JavaScript独自プロファイラ

処理と処理の間の時間を計測する独自プロファイラを作成した。拡張可能なように、関数型コンストラクタにて実装。(jQueryクックブックの5-8を参考にした)

var profiler = function (my, spec){
	var that = {};
        my = my || {};

	var log = [];
	var first;
	var last;
	
	that.time = function(message, since){
		var now = +new Date();
		var seconds = ( now - (since || last )) /1000;
		log.push( seconds.toFixed(3) + ': ' + message );
		return last =+ new Date();
	};
	that.done = function (){
		that.time( 'total' , first);
		return log;
	};
	first = last = + new Date;
	return that;
};

実行する際は以下のようにすれば良い

var p = profiler();
//処理
p.time('first');
//処理
p.time('second');
//処理
p.time('third');
var log = p.done();
//※jQuery利用
$.each(log, function(i, v){
	$("#log").append(v + "<br />");
});

実行時のログ出力例

0.019: first
0.016: second
0.027: third
0.062: total

こちらに実際に実行出来るサンプルがあります。http://blog.livedoor.jp/tshimogaisho/archives/1148608.html