Node.js Performance API 详解:perf_hooks 完全指南

perf_hooks 模块提供高精度性能测量:performance.now()、mark/measure、PerformanceObserver。本文逐一讲解 9 个核心 API 与实战应用。

最佳实践
应用接口与数据存储连接插画

Node.js 性能测量的核心三件套:performance.now() 高精度时间戳、performance.mark()/measure() 标记区间、PerformanceObserver 异步收集测量结果。测量数据可送入指标系统构建完整性能画像。

为什么是 perf_hooks

Date.now() 精度毫秒且受系统时钟回拨影响;perf_hooks 提供单调递增的高精度时间(微秒级)——性能测量的正确工具。它与浏览器 Performance API 对齐,知识跨端复用。

核心 API 速览

const { performance, PerformanceObserver } = require('node:perf_hooks');

// 1. performanceNodeTiming:进程启动各阶段耗时
console.log(performance.nodeTiming);
// { nodeStart, v8Start, bootstrapComplete, ... }

// 2. now():高精度相对时间
const t0 = performance.now();
await work();
console.log(`耗时 ${performance.now() - t0}ms`);

// 3-4. mark + measure:命名标记与区间测量
performance.mark('fetch-start');
await fetchData();
performance.mark('fetch-end');
performance.measure('数据获取', 'fetch-start', 'fetch-end');

// 5. getEntries:查询测量记录
console.log(performance.getEntriesByName('数据获取')[0].duration);

PerformanceObserver:异步收集

const obs = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    metrics.record(entry.name, entry.duration);  // 送指标系统
  }
});
obs.observe({ entryTypes: ['measure', 'function'], buffered: true });

观察器模式让测量代码与上报代码解耦——库代码埋点,应用层决定怎么处理。

实用模式

// 函数耗时装饰
const timed = performance.timerify(myFunction);

// HTTP 请求自动计时(net/http 模块开启)
const { PerformanceResourceTiming } = performance;

performance.timerify() 把任意函数包装成自动计时版本——给存量代码加测量零侵入。

内存与缓冲区

测量条目有默认缓冲上限——高频测量场景用 PerformanceObserver 及时消费,或调大 setResourceTimingBufferSize。长期运行不清理会内存缓慢增长:performance.clearMarks() / clearMeasures() 按需清理。

把 perf_hooks 测量变成持续信号

Performance API 产生的 mark、measure 和事件循环数据首先存在于进程内,并不会自动进入观测云。选择有限的关键阶段,把耗时聚合为指标或记录到自定义 Span,再通过 Prom 采集器或 APM SDK 上报。保留稳定的操作名称,避免把每个请求 ID 变成指标标签;这样才能用长期分布判断优化是否有效。

接入文档:Prometheus 指标采集 · Node.js APM 接入。

常见问题(FAQ)

Q:performance.now() 和 Date.now() 精度差多少?

performance.now() 微秒级单调递增;Date.now() 毫秒级且受 NTP 校时影响(可能跳变)。测耗时永远用前者。

Q:测量本身的开销?

mark/measure 是纳秒级操作,常规使用无感。超高频路径(每请求数千次埋点)才需要考虑采样。

Q:前端那套 Performance API 知识能迁移吗?

能——Node 实现刻意对齐 Web 标准(mark/measure/observer 语义一致),navigator 相关 API 除外。


参考文档

本文依据公开文档整理,示例需按项目依赖版本验证;不将文档中的性能描述视为本项目实测结果。

延伸阅读

获取专属方案

联系我们

加入社区

微信扫码
加入官方交流群

立即体验

在线开通,按量计费,真正的云服务!

立即开始

选择观测云版本

代码托管平台