如何使用Performance API测量代码执行时间?请实现一个性能监控工具
解读
这道题在国内一线/二线前端面试中属于“必考+手写”题型,重点考察三点:
- 是否真正用过 Performance API(而不是只会 console.time);
- 能否把“测量”升级为“监控”,即持续采集、聚合、上报;
- 代码是否兼顾准确性(纳秒级精度)、容错性(兼容低版本浏览器、WebWorker、Node.js 差异)、以及生产可落地(不阻塞主线程、可配置采样率、内存占用可控)。
面试官通常会在你写完基础版本后继续追问:
- 如何区分“首屏”与“可交互”时间?
- 如果用户切换标签页后返回,时间戳是否还准?
- 如何与埋点系统打通,避免重复上报?
- 在 SSR 或微前端场景里,如何对齐 server timing?
因此,答案必须给出“可运行 + 可扩展 + 可插拔”的完整实现,而不是只打印两行 console。
知识点
-
Performance API 族谱
- performance.now():高分辨率时间戳(DOMHighResTimeStamp),单位毫秒,精确到 5μs 以内;不受系统时钟校准影响。
- performance.mark / measure:用户自定义里程碑,自动计算间隔,支持清除。
- PerformanceObserver:异步监听 entry,避免轮询;支持 buffered 标志,可拉回已产生的条目。
- performance.getEntriesByType / getEntriesByName:同步快照,用于降级。
- performance.timeOrigin:页面起始时间(含重定向、DNS、TCP),用于对齐 server timing。
-
精度与误差
- 若页面被挂起(切换标签、息屏),now() 会暂停;返回后连续增长,不会跳跃,但“挂起时长”会被算进区间,需要 visibilitychange 修正。
- 在跨域 iframe 中,now() 基准不同,需统一用 top.performance。
-
内存与采样
- mark/measure 会常驻内存,必须定时 clearMarks/clearMeasures。
- 高频打点(如动画帧)需设置采样率(sampleRate=0.1),避免 entry 爆炸。
-
上报策略
- 优先使用 navigator.sendBeacon,降级用 fetch keepalive;同步上报会阻塞 onbeforeunload。
- 聚合后再上报(如每 200 条或 30s flush 一次),减少 HTTP 数。
-
Node.js 侧
- Node ≥16 自带 performance、PerformanceObserver,但 timeOrigin 单位是纳秒,需除以 1e6 转毫秒。
- 需要 polyfill performance.now() 的场景(< v8.5)可用 process.hrtime.bigint()。
答案
下面给出一份“生产级”性能监控工具 PerfMonitor,支持浏览器与 Node.js 双端,内置采样率控制、内存回收、visibilitychange 修正、以及可插拔上报器。可直接复制到简历项目或现场手写。
/**
* 生产级性能监控工具 PerfMonitor
* 支持浏览器与 Node.js,兼容低版本(< Safari 14)降级
* usage:
* const pm = new PerfMonitor({ sampleRate: 0.2, reportUrl: '/perf' });
* pm.mark('startRender');
* ...业务代码...
* pm.measure('startRender', 'renderDone');
* pm.destroy(); // 页面卸载时调用,防止内存泄漏
*/
class PerfMonitor {
constructor(options = {}) {
this.sampleRate = Math.max(0, Math.min(1, options.sampleRate ?? 1));
this.reportUrl = options.reportUrl ?? '';
this.bufferSize = options.bufferSize ?? 200;
this.buffer = [];
this.marks = new Map(); // 本地缓存,防止 mark 被 clear 后丢失
this.handles = []; // 保存句柄,用于 destroy
this._initObserver();
this._initVisibilityHack();
}
/* ------------------ 核心 API ------------------ */
mark(name) {
if (Math.random() > this.sampleRate) return;
try {
performance.mark(name);
this.marks.set(name, this.now());
} catch (e) {
this.marks.set(name, this.now()); // 降级
}
}
measure(name, startMark, endMark) {
if (Math.random() > this.sampleRate) return;
try {
performance.measure(name, startMark, endMark);
} catch (e) {
// 降级:手动计算
const start = this.marks.get(startMark) ?? 0;
const end = this.marks.get(endMark) ?? this.now();
this._push({
name,
entryType: 'measure',
startTime: start,
duration: end - start
});
}
}
now() {
return (typeof performance !== 'undefined' ? performance.now() : Date.now());
}
/* ------------------ 私有方法 ------------------ */
_initObserver() {
if (typeof PerformanceObserver === 'undefined') {
// 降级:定时同步拉取
this._pollTimer = setInterval(() => this._syncPoll(), 1000);
return;
}
const observer = new PerformanceObserver(list => {
list.getEntries().forEach(entry => this._push(entry));
});
observer.observe({ type: 'mark', buffered: true });
observer.observe({ type: 'measure', buffered: true });
this.handles.push(() => observer.disconnect());
}
_syncPoll() {
['mark', 'measure'].forEach(type => {
(performance.getEntriesByType(type) || []).forEach(e => this._push(e));
performance.clearMarks();
performance.clearMeasures();
});
}
_push(entry) {
this.buffer.push({
n: entry.name,
t: Math.round(entry.startTime + performance.timeOrigin), // 绝对时间戳
d: Math.round(entry.duration * 100) / 100, // 保留两位小数
u: navigator.userAgent.slice(0, 200) // 简版 UA
});
if (this.buffer.length >= this.bufferSize) this._flush();
}
_flush() {
if (!this.buffer.length || !this.reportUrl) return;
const body = JSON.stringify({ perf: this.buffer });
this.buffer = [];
if (navigator.sendBeacon) {
navigator.sendBeacon(this.reportUrl, body);
} else {
fetch(this.reportUrl, { method: 'POST', body, keepalive: true }).catch(() => {});
}
}
_initVisibilityHack() {
// 修正挂起时段导致的“虚高”
let hiddenTime = 0;
const onVis = () => {
if (document.hidden) {
hiddenTime = performance.now();
} else if (hiddenTime) {
const delta = performance.now() - hiddenTime;
this._push({ name: '_visResume', entryType: 'measure', startTime: hiddenTime, duration: delta });
hiddenTime = 0;
}
};
document.addEventListener('visibilitychange', onVis);
this.handles.push(() => document.removeEventListener('visibilitychange', onVis));
}
destroy() {
this._flush();
this.handles.forEach(fn => fn());
if (this._pollTimer) clearInterval(this._pollTimer);
}
}
/* ------------------ Node.js 端兼容 ------------------ */
if (typeof module !== 'undefined' && module.exports) {
const { performance, PerformanceObserver } = require('perf_hooks');
global.performance = performance;
global.PerformanceObserver = PerformanceObserver;
module.exports = PerfMonitor;
}
使用示例(浏览器):
const pm = new PerfMonitor({ sampleRate: 1, reportUrl: '/gateway/perf' });
pm.mark('routeStart');
await fetch('/api/data');
pm.mark('routeEnd');
pm.measure('apiCost', 'routeStart', 'routeEnd');
window.addEventListener('beforeunload', () => pm.destroy());
Node 端同理,不再赘述。
拓展思考
- 首屏可交互(TTI)怎么测?
可监听 PerformanceObserver 的 ‘longtask’ 与 ‘resource’,结合 FCP、DCL 计算静默窗口(5s 内无长任务且网络空闲)。 - 如何与 Server Timing 对齐?
服务端在响应头加Server-Timing: db;dur=123, cache;dur=12,前端通过performance.getEntriesByType('navigation')[0].serverTiming拿到,减去后可得“纯前端”耗时。 - 微前端/iframe 场景?
统一用top.performance作为时间基准,iframe 内部通过postMessage把 entry 序列化后抛到主应用聚合,避免时间原点不一致。 - 大数据量优化?
- 使用 Reservoir Sampling 固定内存;
- 对重名 measure 做直方图聚合(p50/p90/p99)后再上报;
- 利用 WebWorker 做压缩(gzip),减少主线程压力。
- 安全与隐私?
上报前脱敏:URL 去掉 query、UA 截断、用户 ID 哈希化;遵循《个人信息保护法》,提供 opt-out 接口。