3

Example code:

const got = require('got');
async function timeSpent (){
   const time = new Date().getTime()
   await got('***')
   return new Date().getTime() - time
}

I wonder if there is a better way?

SuperStormer
  • 4,997
  • 5
  • 25
  • 35
ebyte
  • 1,469
  • 2
  • 17
  • 32
  • You can find alternatives here. https://stackoverflow.com/questions/313893/how-to-measure-time-taken-by-a-function-to-execute – robinvrd Feb 19 '20 at 09:53

5 Answers5

3

It's not required to implement your own timing logic when using got.

The response includes a timings object that collects all millis spent per phase.

You only need to read out timings.phases.total from the response object.

const path = "http://localhost:3000/authenticate";
const response = await got.post(path, {
  body: { username: "john_doe", password: "mypass" },
  json: true,
  headers: {
    Accept: "application/json",
    "Content-type": "application/json",
  },
});

logger.debug({type: 'performance', path, duration: response.timings.phases.total});

Reference:

https://github.com/sindresorhus/got#timings

https://github.com/sindresorhus/got/pull/590

Nico Van Belle
  • 4,911
  • 4
  • 32
  • 49
2

You can go through this way.

console.time('test1');
console.time('test2');

setTimeout( (elem) => {
   console.log('You want to write something here!!');
   console.timeEnd('test2');
}, 2000);

console.timeEnd('test1');
2

You may use a 3rd Party statman-stopwatch to easily record the total time.

Example

const got = require('got');
const Stopwatch = require('statman-stopwatch');
async function timeSpent (){
    const sw = new Stopwatch();
    sw.start();
    await got('***');
    sw.stop();
    const delta = sw.read();
  return delta;
}
1

performance - is a native way to measure things like this.

const got = require('got');
async function timeSpent (){
  var t0 = performance.now();
  await got('***')
  var t1 = performance.now();
  console.log("Call to do something took " + (t1 - t0) + " milliseconds.");
  return t1 - t0;
}

Check browser support https://caniuse.com/#search=performance

qiAlex
  • 4,290
  • 2
  • 19
  • 35
1
 let currentDate = moment().format('YYYY/MM/DD HH:mm')
            let dataCalca = moment(dataValue).format('YYYY/MM/DD HH:mm')
            let hours = moment
              .duration(moment(currentDate, 'YYYY/MM/DD HH:mm')
                .diff(moment(dataCalca, 'YYYY/MM/DD HH:mm'))
              ).asHours();

So you get the numbers as an hour. You can calculate with that

Allen Bert
  • 158
  • 2
  • 5
  • 20