Browser console and calculating multiple javascript execution time differences

前端 未结 2 1917
耶瑟儿~
耶瑟儿~ 2021-01-26 15:25

I can easily do this:

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

But is it possible to calculate time in multiple f

相关标签:
2条回答
  • 2021-01-26 15:59

    There is a solution which is a living standard. Seems like its already on chrome and major browsers and nodejs

    https://developer.mozilla.org/en-US/docs/Web/API/Console/timeLog

    console.time("answer time");
    alert("Click to continue");
    console.timeLog("answer time");
    alert("Do a bunch of other stuff...");
    console.timeEnd("answer time");
    The
    
    0 讨论(0)
  • 2021-01-26 16:13

    If you need times on particular function, I guess you know that they can be achieved with argument to console.time() and console.timeEnd(). More info about it here https://developers.google.com/chrome-developer-tools/docs/console/ .

    From my understanding of your question you need laps for benchmark analysis.

    I have defined following methods which you can use to get lap times in milliseconds.


    Update : Using performance api which is recommended API for such use cases.

    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]
    }
    

    Note that this is rough code and should be run only in dev. Otherwise it might leave bad traces in global object and bad taste on your mouth.

    0 讨论(0)
提交回复
热议问题