How do I measure the execution time of JavaScript code with callbacks?

前端 未结 10 1487
臣服心动
臣服心动 2020-11-30 16:28

I have a piece of JavaScript code that I am executing using the node.js interpreter.

for(var i = 1; i <         


        
10条回答
  •  遥遥无期
    2020-11-30 17:00

    Surprised no one had mentioned yet the new built in libraries:

    Available in Node >= 8.5, and should be in Modern Browers

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

    https://nodejs.org/docs/latest-v8.x/api/perf_hooks.html#

    Node 8.5 ~ 9.x (Firefox, Chrome)

    // const { performance } = require('perf_hooks'); // enable for node
    const delay = time => new Promise(res=>setTimeout(res,time))
    async function doSomeLongRunningProcess(){
      await delay(1000);
    }
    performance.mark('A');
    (async ()=>{
      await doSomeLongRunningProcess();
      performance.mark('B');
      performance.measure('A to B', 'A', 'B');
      const measure = performance.getEntriesByName('A to B')[0];
      // firefox appears to only show second precision.
      console.log(measure.duration);
      // apparently you should clean up...
      performance.clearMarks();
      performance.clearMeasures();         
      // Prints the number of milliseconds between Mark 'A' and Mark 'B'
    })();

    https://repl.it/@CodyGeisler/NodeJsPerformanceHooks

    Node 12.x

    https://nodejs.org/docs/latest-v12.x/api/perf_hooks.html

    const { PerformanceObserver, performance } = require('perf_hooks');
    const delay = time => new Promise(res => setTimeout(res, time))
    async function doSomeLongRunningProcess() {
        await delay(1000);
    }
    const obs = new PerformanceObserver((items) => {
        console.log('PerformanceObserver A to B',items.getEntries()[0].duration);
          // apparently you should clean up...
          performance.clearMarks();
          // performance.clearMeasures(); // Not a function in Node.js 12
    });
    obs.observe({ entryTypes: ['measure'] });
    
    performance.mark('A');
    
    (async function main(){
        try{
            await performance.timerify(doSomeLongRunningProcess)();
            performance.mark('B');
            performance.measure('A to B', 'A', 'B');
        }catch(e){
            console.log('main() error',e);
        }
    })();
    

提交回复
热议问题