Calculate function execution time

Viewed 253

Suppose I have called a function as,

const data = await someFunction()

I want to calculate execution time of this function.

For this I tried as,

let startTime = Date.now();
const data = await someFunction()
let endTime = Date.now();

And I calculated difference between endTime-startTime and the result I get i think is in millisecond and converted it to second.

I would like second opinion on this whether this is one of the option to calculate or is there some more better method which can give me execution time in second.

2 Answers

Yep there are a couple more interesting methods:

  1. More accurate way to test in node is using:

    const start = process.hrtime()
    // awaited function
    const result = process.hrtime(start);
    
    // This will give results in nanoseconds
    
  2. Another interesting way is to use performance hooks:

    const { PerformanceObserver, performance } = require('perf_hooks');
    
    const obs = new PerformanceObserver((items) => {
      console.log(items.getEntries()[0].duration);
      performance.clearMarks();
    });
    
    obs.observe({ entryTypes: ['measure'] });
    
    performance.mark('A');
    // await your function
    performance.mark('B');
    performance.measure('A to B', 'A', 'B');
    

Have you been trying console.time() ?

console.time("Some Function time");
const data = await someFunction()
console.timeEnd("Some Function time");
Related