Search code examples
javascriptnode.jsperformanceasync-awaitmeasure

How to measure the execution time of an asynchronous function in nodejs?


I'm trying to get the execution/response time of an asynchronous function that executes inside a node-fetch operation, like the following

async function getEditedData() {      
       var a = await fetch(`https://api.example.com/resorce_example`);
       var b = await a.json();
       // Some aditional treatment of the object obtained (b)
       console.log("End of the asynchronous function")
}

I Used the library perf_hooks like this, but the execution time shows before

const hrtime = require ('perf_hooks').performance.now ;
var start = hrtime ();
   getEditedData();
var end   = hrtime ();
console.log (end - start);

I found the async_hooks library https://nodejs.org/api/perf_hooks.html#perf_hooks_measuring_the_duration_of_async_operations , but I can´t understand how it works. I am a basic in javascript/nodejs


Solution

  • You could simply store Date.now() in some variable and then check Date.now() when your Promise resolves (or rejects) and subtract to find the difference. For example:

    const simulateSomeAsyncFunction = new Promise((resolve, reject) => {
      console.log('Initiating some async process, please wait...')
      const startTime = Date.now();
    
      setTimeout(() => {
        resolve(Date.now() - startTime);
      }, 3000);
    });
    
    simulateSomeAsyncFunction.then(msElapsed => {
      console.log(`Async function took ${msElapsed / 1000} seconds to complete.`);
    });

    Note: You could write code that achieves the same thing and appears to be synchronous by using await/async since that is just "syntactic sugar" built on top of Promises. For example:

    const simulateSomeAsyncFunction = () => {
      console.log('Initiating some async process, please wait...');
    
      return new Promise((resolve, reject) => {
        setTimeout(resolve, 3000);
      });
    };
    
    // Await is required to be called within an async function so we have to wrap the calling code in an async IIFE
    (async() => {
      const startTime = Date.now();
    
      await simulateSomeAsyncFunction();
    
      const msElapsed = Date.now() - startTime;
    
      console.log(`Async function took ${msElapsed / 1000} seconds to complete.`);
    })();