LoginSignup
90
90

More than 5 years have passed since last update.

console.time()で非同期処理の所要時間を計測する

Last updated at Posted at 2013-06-20

console.time('label_name')console.timeEnd('label_name')を使うと経過時間の測定が簡単にできる。

基本的な使い方

測りたい処理の開始時にconsole.time()を呼び出す。このとき引数にラベル名を渡す必要がある。
計測終了したいタイミングでconsole.timeEnd()を呼び出す。このとき引数には同じラベル名を渡す。

function loop(){
    console.time("loop time");
    for(var i =0; i < 1000000000; i++){}
    console.timeEnd("loop time");
}
loop();

出力結果

loop time: 812.000ms 

jQueryのDeferredと組み合わせて使う

便利だからDeferredと組み合わせて使う (※Deferredを使う必要性は特にない)

なんかJSONとってくる関数
$(function(){

    // 宣言
    function asyncFunction(){
        console.time('measurement of time'); // 計測開始
        var def = $.Deferred();

        $.ajax({
            url : 'hoge.json',
            type: 'GET',
            dataType : 'json'
        }).then(function(json){
            console.timeEnd('measurement of time'); // 計測終了(成功)
            def.resolve(json);
        },function(){
            console.timeEnd('measurement of time'); // 計測終了(失敗)
            def.reject('fail fail fail fail fail...!!');
        });

        return def.promise();
    }

    // 呼び出し
    asyncFunction().then(function(json){
        console.log(' :) ');
    },function(){
        console.log(' :( ');
    });
});

出力結果

measurement of time: 5.000ms
:)

console便利


参考URL:Console API

90
90
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
90
90