0

I can easily do this:

console.time('mytimer');
doSomeWork();
console.timeEnd('mytimer');

But is it possible to calculate time in multiple functions. I need to define the script's start time in a global variable. Then inside multiple functions I will write how many miliseconds passed since the start of the time. And write the name of the function Something like this:

console.time('mytimer');
doSomeWork() {
  // console.log(difference between now and "mytimer"s start time)
  // console.log(name of the function: doSomeWork())
};
doSomeWork2() {
  // console.log(difference between now and "mytimer"s start time)
  // console.log(name of the function: doSomeWork2())
};
doSomeWork3() {
  // console.log(difference between now and "mytimer"s start time)
  // console.log(name of the function: doSomeWork3())
};
console.timeEnd('mytimer');

I will use this in Chrome 26+ for debug issues so using browser dependent functions (for example: arguments.callee.name) is not a problem.

Edit: To clearize my problem.
This works:

console.time('myTimer1');
console.timeEnd('myTimer1');

This doesn't work:

console.time('myTimer2');
console.time('myTimer2');

Edit: Of course it is possible to write too much timers and check time of each of them. But I need to know elapsed time since the javascript code is started in each lap.

4

2 に答える 2

1

特定の関数で時間が必要な場合は、console.time() と console.timeEnd() の引数を使用して達成できることを知っていると思います。詳細については、https://developers.google.com/chrome-developer-tools/docs/console/をご覧ください。

あなたの質問に対する私の理解から、ベンチマーク分析にはラップが必要です。

ラップタイムをミリ秒単位で取得するために使用できる次のメソッドを定義しました。


更新: このようなユースケースに推奨される API であるパフォーマンスAPI を使用します。

console.lapStart = function(name){
     window[name] = window[name] || {};
     window[name].globalTimer = performance.now();
}
console.showLap = function(name){
     currTime = performance.now();
     var diff = currTime  - window[name].globalTimer;
     console.log(arguments.callee.name, diff);
}
console.lapEnd = function(name){
     currTime = performance.now();
     var diff = currTime  - window[name].globalTimer;
     console.log(arguments.callee.name, diff);
     delete window[name]
}

これは大まかなコードであり、dev でのみ実行する必要があることに注意してください。そうしないと、グローバル オブジェクトに悪い痕跡が残り、口に悪い味が残る可能性があります。

于 2013-05-26T16:27:10.457 に答える