You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用got库时如何更优计算请求耗时?求更佳实现方案

如何用Got库精准统计HTTP请求耗时

嘿,你的手动计时思路没问题,但其实Got本身就内置了更专业的请求耗时统计能力,比手动用Date.getTime()要精准、便捷得多,而且还能拆分请求各阶段的耗时,方便排查性能问题。

最优实现:使用Got内置的timings功能

Got支持通过开启timings选项,自动记录请求从发起到完成的全流程时间,并且会在响应对象中返回各个阶段的耗时数据:

const got = require('got');

async function getRequestTimings() {
  try {
    const response = await got('https://example.com', {
      timings: true // 开启计时功能
    });

    // 获取总耗时(毫秒级)
    const totalDuration = response.timings.phases.total;
    console.log(`请求总耗时:${totalDuration.toFixed(2)}ms`);

    // 查看各细分阶段的耗时,方便排查性能瓶颈
    console.log('各阶段耗时详情:');
    console.log(`DNS解析:${response.timings.phases.dns?.toFixed(2) || 0}ms`);
    console.log(`TCP连接建立:${response.timings.phases.tcp?.toFixed(2) || 0}ms`);
    console.log(`TLS握手(HTTPS):${response.timings.phases.tls?.toFixed(2) || 0}ms`);
    console.log(`等待响应首字节:${response.timings.phases.firstByte?.toFixed(2) || 0}ms`);
    console.log(`响应体下载:${response.timings.phases.download?.toFixed(2) || 0}ms`);
  } catch (error) {
    console.error('请求出错:', error.message);
  }
}

getRequestTimings();

为什么这是最优方案?

  • 精度更高:Got内部使用process.hrtime()计时(纳秒级精度),比Date.getTime()的毫秒级精度更准确,而且不受系统时间调整的影响。
  • 维度更全:能拆分请求的各个关键阶段,当请求变慢时,可以快速定位是DNS解析慢、TCP连接慢还是响应返回慢。
  • 代码更简洁:无需手动管理时间戳,直接从响应对象中获取统计数据即可。

如果坚持手动计时的优化版本

如果你还是偏好手动统计总耗时,建议用process.hrtime()代替Date.getTime(),避免系统时间波动带来的误差:

const got = require('got');

async function calculateTotalTime() {
  const startTime = process.hrtime();
  await got('https://example.com');
  const [seconds, nanoseconds] = process.hrtime(startTime);
  // 转换为毫秒并保留两位小数
  return (seconds * 1000 + nanoseconds / 1e6).toFixed(2);
}

// 调用示例
calculateTotalTime().then(time => console.log(`总耗时:${time}ms`));

内容的提问来源于stack exchange,提问作者ebyte

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 18:14:08