got,如何计算花费的时间?

问题描述 投票:1回答:5

示例代码:

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

我想知道是否有更好的方法?

javascript node.js xmlhttprequest got
5个回答
1
投票

performance-是一种测量此类事物的本地方法。

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;
}

检查浏览器支持https://caniuse.com/#search=performance


1
投票

您可以使用第三方statman-stopwatch轻松记录总时间。

示例

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;
}

0
投票

您可以通过这种方式。

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

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

console.timeEnd('test1');

0
投票
 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();

所以您得到的数字是一个小时。你可以用这个来计算


0
投票

使用got时,不需要实现自己的定时逻辑。

响应包括一个计时对象,该对象收集每个阶段花费的所有毫毫秒。

您只需要读出以下属性timings.phases.total。来自响应对象

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.infoMetadata({type:'performance', path, duration:response.timings.phases.total});

参考:

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

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


推荐问答