使用 process.hrtime.bigint 测量函数耗时,并换算为纳秒

解读

国内一线/二线厂面试时,这道题常作为“性能诊断”环节的敲门砖,考察三点:

  1. 是否知道高精度时间戳 API 的演进(Date.now → process.hrtime → process.hrtime.bigint);
  2. 能否规避大数精度陷阱,正确输出纳秒单位;
  3. 是否具备封装成可复用工具函数的意识,并能在高并发场景下保持低开销。

很多候选人直接答“结束减开始”,却忽略 bigint 字面量、单位换算、GC 影响,导致扣分。

知识点

  • process.hrtime.bigint() 返回当前系统单调时钟的 bigint 纳秒值,不受系统时间跳变影响;
  • 1 毫秒 = 1 000 000 纳秒,1 秒 = 1 000 000 000 纳秒;
  • bigint 运算必须使用 BigInt 字面量或 BigInt() 构造函数,Number 混用会抛 TypeError;
  • 在热路径中频繁创建 bigint 会触发 GC,需权衡精度与开销;
  • 纳秒级结果通常用模板字符串或 toString() 输出,避免科学计数法失真;
  • 若需微秒/毫秒展示,应显式做整数除法,而非先转 Number(大数溢出)。

答案

/**
 * 高精度测量函数耗时(纳秒)
 * @param {Function} fn 待测函数
 * @param {...any} args 透传给 fn 的参数
 * @returns {{result: any, ns: string}} result 为函数返回值,ns 为耗时(单位:纳秒,字符串形式防精度丢失)
 */
function measureNs(fn, ...args) {
  const start = process.hrtime.bigint();   // 起点,bigint 纳秒
  const result = fn(...args);              // 执行待测逻辑
  const end = process.hrtime.bigint();     // 终点
  const delta = end - start;               // 仍是 bigint
  return { result, ns: delta.toString() }; // 返回字符串避免精度问题
}

/* === 使用示例 === */
function demo() {
  let sum = 0;
  for (let i = 0; i < 1e6; i++) sum += i;
  return sum;
}

const { result, ns } = measureNs(demo);
console.log(`结果=${result}, 耗时=${ns} ns`); // 结果=499999500000, 耗时=582300 ns

拓展思考

  1. 微基准陷阱:for 空循环会被 V8 优化掉,需加入“真实负载”或 benchmark.js 做统计;
  2. 多核场景:若函数内部异步跳转事件循环,单次测量可能不准,应采样多次取 P50/P99;
  3. 线上埋点:可把 delta 直接上报监控系统(如阿里云 SLS、字节 Slardar),但 bigint 需序列化为字符串;
  4. Worker Threads:在子线程里同样可用 process.hrtime.bigint(),但时钟基准与主线程一致,可放心横向对比;
  5. 与 performance.now 对比:浏览器端无 bigint 版本,Node 端 performance.now 返回毫秒双精度浮点,精度仅 5μs 级,不适合纳秒级诊断。