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

前端 未结 10 1379
臣服心动
臣服心动 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条回答
  • For anyone want to get time elapsed value instead of console output :

    use process.hrtime() as @D.Deriso suggestion, below is my simpler approach :

    function functionToBeMeasured() {
        var startTime = process.hrtime();
        // do some task...
        // ......
        var elapsedSeconds = parseHrtimeToSeconds(process.hrtime(startTime));
        console.log('It takes ' + elapsedSeconds + 'seconds');
    }
    
    function parseHrtimeToSeconds(hrtime) {
        var seconds = (hrtime[0] + (hrtime[1] / 1e9)).toFixed(3);
        return seconds;
    }
    
    0 讨论(0)
  • 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);
        }
    })();
    
    0 讨论(0)
  • 2020-11-30 17:00

    You could give Benchmark.js a try. It supports many platforms among them also node.js.

    0 讨论(0)
  • 2020-11-30 17:01

    I had same issue while moving from AWS to Azure

    For express & aws, you can already use, existing time() and timeEnd()

    For Azure, use this: https://github.com/manoharreddyporeddy/my-nodejs-notes/blob/master/performance_timers_helper_nodejs_azure_aws.js

    These time() and timeEnd() use the existing hrtime() function, which give high-resolution real time.

    Hope this helps.

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