1
const {performance} = require('perf_hooks');
let startTime = performance.now();
const extractedData = await readFunction()
let endTime = performance.now();
let timeTaken = endTime-startTime

I want to calculate time taken to execute readFunction(). Is this good approach to calculate total time taken to execute readFunction? Also on console.log(startTime) it gives some value instead of starting from 0.

So to get precise value should I do the following step or above step is enough to get precise time in milisecond.

const {performance} = require('perf_hooks');
let startTime = 0
const extractedData = await readFunction()
let endTime = performance.now();
let timeTaken = endTime-startTime

Is timeTaken value in milisecond? If anyone needs any further information please let me know.

Siva Pradhan
  • 791
  • 1
  • 6
  • 23
  • 2
    Have you read up on what `performance.now()` returns? https://developer.mozilla.org/en-US/docs/Web/API/Performance/now Also, subtracting `0` from any value is the same as using the value itself. So `endTime - startTime` where `startTime === 0` is the same as `endTime`. – Felix Kling Apr 19 '21 at 10:21
  • What's the difference between the first and second snippet? – Bergi Apr 19 '21 at 10:22
  • 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) – luk2302 Apr 19 '21 at 10:22
  • @FelixKling in first snippet on console.log(startTime) gives value say, 1325, where as in second snippte console.log(startTime) will be from . – Siva Pradhan Apr 19 '21 at 10:31

1 Answers1

0
function calculateTime(yourFunction) {
  console.time();
  yourFunction();
  return console.timeEnd();
}
async function calculateTimeForPromises(yourPromise) {
  console.time();
  await yourPromise();
  return console.timeEnd();
}

Is that helpful?

StPaulis
  • 2,844
  • 1
  • 14
  • 24