2

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.

Siva Pradhan
  • 791
  • 1
  • 6
  • 23
  • 2
    Does this answer your question? [How to measure time taken by a function to execute](https://stackoverflow.com/questions/313893/how-to-measure-time-taken-by-a-function-to-execute) – Erfan Geramian Apr 21 '21 at 07:07

2 Answers2

3

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');
    
Alexandru Olaru
  • 6,842
  • 6
  • 27
  • 53
1

Have you been trying console.time() ?

console.time("Some Function time");
const data = await someFunction()
console.timeEnd("Some Function time");
lamboktulus1379
  • 350
  • 1
  • 4
  • 10