JavaScript で時間計測処理を実装する
関数をパラメータに取り、その所要時間(秒数)を出力する関数を定義する。
print はユーザ定義のメソッド。
1 2 3 4 5 6 7 8 9 10 | var Timer = function () {}; Timer.timeit = function (description) { return function (func) { var start = ( new Date).getTime(); func(); var elapse = (( new Date).getTime() - start) / 1000; print(description + ": " + elapse + " sec" ); }; }; |
以下は JScript(WSH) で500ミリ秒のスリープを行う例
1 2 3 4 | // test code for WSH var print = function (msg) { WScript.echo(msg); }; Timer.timeit( "test code" )( function () { WScript.sleep(500); }); |
出力例
1 | test code: 0.5 sec |
インスタンスメソッドで時間測定をしたい場合は、組み込み Function オブジェクトに
このような bind メソッドを定義すると便利だ。 (prototype.js 等を参照)
1 2 3 4 | Function.prototype.bind = function (context) { var method = this ; return function () { return method.apply(context, arguments); }; }; |
呼び出し例
1 2 3 4 5 6 7 8 9 10 11 12 13 | // test code for WSH var Klass = function (x) { this .x = x; }; Klass.prototype.f = function () { Timer.timeit( "Klass.f" )( function () { WScript.sleep( this .x); }.bind( this )); }; var klass = new Klass(1000); klass.f(); |
出力例
1 | Klass.f: 1 sec |
0 件のコメント:
コメントを投稿