【问题标题】:How to calculate the time spent when using got?使用got时如何计算花费的时间?
【发布时间】:2020-06-03 10:38:45
【问题描述】:

示例代码:

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

不知道有没有更好的办法?

【问题讨论】:

标签: javascript node.js time xmlhttprequest node.js-got


【解决方案1】:

性能 - 是衡量此类事物的原生方式。

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

【讨论】:

    【解决方案2】:

    你可以通过这条路。

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

    【讨论】:

      【解决方案3】:

      您可以使用第三方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;
      }
      

      【讨论】:

        【解决方案4】:
         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();
        

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

        【讨论】:

          【解决方案5】:

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

          参考:

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

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-09-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多