0

I have a node file which contains many methods including a Async call method which fetches data from db. I need to find the exact execution time of it.

So i tried,

.
.
var start = Date.now();
await dbFetching()
var end = Date.now();
console.log(end - start)
.

Then I tried with an external shell script which executes the file and find the actual time execution of the entire file execution. But the issue is i need to calculate only the time taken for the Async call (dbFetching). Below is my shell script,

#!/bin/sh

START=$(date +%s)
node ./s3-glacier.js
END=$(date +%s)
DIFF=$(( $END - $START ))
echo "It took $DIFF seconds"

But i though like, if i can run entire node script in the shell script, May be i can calculate the time. Therefore suggest your thought on this to calculate only the Async time consumption. Thanks in advance

ahkam
  • 607
  • 7
  • 24
  • "I need to find the exact execution time of it." Don't rely on one measurement of an async call. If you try 100 repetitions, you may see quite a spread of times. Quite a bit happens internally and there are various sources of randomness. Beware. – Paul May 21 '21 at 07:47
  • yes. It doesn't matter if the time change for every iterations. But i need to find an execution time of a single async call – ahkam May 21 '21 at 08:02

1 Answers1

0

If you have this possibility - use async/await. It would look like:

var start = Date.now();
await dbFetching(); // blocks execution of code
var end = Date.now(); // this happens AFTER you've fetched the data
console.log(end - start)

That would require your function to be marked as async though, or return a Promise.

Otherwise you'd need to pass a callback to a function, so that the function calls it when it's done and you know that it's now time to calculate the dime. Something along the lines of:

var start = Date.now();
dbFetching(function done() { // done should be called AFTER the data is fetched
  var end = Date.now();
  console.log(end - start)
})

Andrey Popov
  • 7,362
  • 4
  • 38
  • 58
  • actually i forgot to mentioned that the function is properly handed with async await scenario. But the fetching takes too time than the console time difference. It's because of the async behaviour – ahkam May 21 '21 at 07:52
  • the solution is wrong because of DST – Alexey Sh. Apr 14 '23 at 18:53