AI 代码审查实战:Node.js perf_hooks 的九个计时契约测试
AI 很容易写出看似专业的计时包装:调用开始时 mark,结束时 measure,再挂一个 PerformanceObserver 打印结果。真正的审查难点通常藏在输出之外:结束边界是否真的等待了工作,条目是否被清理,回调何时执行,元数据是否还在引用原对象,以及失败后是否留下误导性的成功记录。
本文把这些问题拆成九个可独立运行的契约测试。实测环境为 Node.js v24.19.0;每段代码都能单独保存为对应的 .mjs 文件,用 node 加文件名运行,不依赖 npm 包、不连接网络,也不依赖前一段代码留下的状态。这里的版本号是测试环境记录,并不是对当前最新版的声明。
所有成功运行的标准输出都固定不变:只显示断言通过后的布尔结论。真实时钟产生的数值只在程序里验证有限性、非负性或相对关系,绝不拿某次读数作为预期输出。显式时间戳属于测试夹具,也不会被包装成基准测试结果。全文重点是计时接口的使用契约,不评判算法、模型或硬件谁更快。
阅读时先识别三种角色:mark 表示一个点,measure 表示由边界计算的区间,观察器负责接收条目。查询时间线、观察器待交付队列、你自己保存的对象引用又各有生命周期。把这些角色画清楚,再请 AI 修改代码,比笼统地要求优化性能更容易得到可以验证的答案。

接口范围核对:Node.js v24.19.0 官方性能测量文档。下文代码与输出由该版本逐段运行验证。
一、先验证时间点的形状,再讨论耗时
审查 AI 生成的埋点代码时,第一步可以很小:创建一个标记,马上查询它,再核对类型和数值边界。这里把调用前后的高分辨率时间作为包围区间,允许两个读数相等。测试只要求有限、非负且次序正确,不要求微小操作一定跨过某个可见的时间刻度。
标记记录的是一个时间点,持续时间应为零。名称和条目类型一起筛选,能避免同名的测量条目混进结果。所有方法都保留 performance 作为接收对象,复制代码时不要随手把方法解构成失去接收者的裸函数。
文件:01-mark-shape.mjs。运行方式:node 01-mark-shape.mjs。
import assert from 'node:assert/strict';
import { performance } from 'node:perf_hooks';
const name = 'review:shape';
try {
const before = performance.now();
const mark = performance.mark(name);
const after = performance.now();
for (const value of [before, mark.startTime, after, mark.duration]) {
assert.ok(Number.isFinite(value) && value >= 0);
}
assert.ok(before <= mark.startTime && mark.startTime <= after);
assert.equal(mark.entryType, 'mark');
assert.equal(mark.duration, 0);
assert.equal(mark.name, name);
assert.equal(performance.getEntriesByName(name, 'mark').length, 1);
console.log('markShape=true; boundedClock=true');
} finally {
performance.clearMarks(name);
}确定输出:
markShape=true; boundedClock=true
这一例没有打印实际时间,因此在繁忙机器上也能保持相同输出。它能发现字段理解错误、查询条件错误和时钟混用,却无法告诉你某段业务是否足够快。把正确性断言与服务的性能目标分开,审查意见才不会把一次偶然读数写成可靠结论。
二、命名区间要覆盖真正等待的工作
第二个例子用两个具名标记包住一次异步操作。这里的异步工作只是返回固定结果的函数,重点是代码把结束标记放在 await 之后。如果 AI 把结束标记提前到 Promise 刚创建的位置,测到的边界就会偏离调用者真正等待的工作。
测量条目的起点必须对应开始标记,持续时间必须等于终点减起点。两个时刻非常接近时,结果可以是零,所以测试采用非负条件而不是严格大于零。示例还检查测量完成后两个标记仍然存在,提醒调用者为它们安排清理。
文件:02-named-span.mjs。运行方式:node 02-named-span.mjs。
import assert from 'node:assert/strict';
import { performance } from 'node:perf_hooks';
const startName = 'review:job:start';
const endName = 'review:job:end';
const spanName = 'review:job:span';
try {
const start = performance.mark(startName);
const result = await (async () => 'done')();
const end = performance.mark(endName);
const span = performance.measure(spanName, startName, endName);
assert.equal(result, 'done');
assert.equal(span.entryType, 'measure');
assert.equal(span.startTime, start.startTime);
assert.equal(span.duration, end.startTime - start.startTime);
assert.ok(Number.isFinite(span.duration) && span.duration >= 0);
assert.equal(performance.getEntriesByName(startName, 'mark').length, 1);
assert.equal(performance.getEntriesByName(endName, 'mark').length, 1);
console.log('awaitedBoundary=true; namedSpan=true');
} finally {
performance.clearMarks(startName);
performance.clearMarks(endName);
performance.clearMeasures(spanName);
}确定输出:
awaitedBoundary=true; namedSpan=true
真实服务需要先决定异常是否也要计时,以及记录业务失败时是否允许埋点再次抛错。这里仅演示成功路径,finally 负责收尾,并没有悄悄把异常转成成功。另一个常见隐患是并发请求共用开始名称;应让一次操作拥有自己的名称或直接保存数值边界,避免后来的请求改变名称解析所指向的时间点。
三、清理标记、清理测量是两件事
让 AI 补一行清理代码很容易,判断它清理了谁却需要测试。下面故意创建两个同名标记、一个旁观标记,以及一个与标记同名的测量。按名称清理标记之后,同名标记都应消失,旁观标记与测量则各自保留。这组反例能挡住把名称当唯一键的错误理解。
在共享进程里,库函数不应随意无参数清空整个时间线。示例始终点名自己的条目,避免删除其他组件的观察数据。测量对象已经被变量引用时,从时间线移除它也不会使变量凭空失效;这提示我们同时审查查询缓冲区和业务代码持有的引用。
文件:03-clear-lifecycle.mjs。运行方式:node 03-clear-lifecycle.mjs。
import assert from 'node:assert/strict';
import { performance } from 'node:perf_hooks';
const shared = 'review:clear:shared';
const other = 'review:clear:other';
try {
performance.mark(shared, { startTime: 1 });
performance.mark(shared, { startTime: 3 });
performance.mark(other, { startTime: 2 });
const span = performance.measure(shared, { start: 0, end: 4 });
assert.equal(performance.getEntriesByName(shared, 'mark').length, 2);
performance.clearMarks(shared);
assert.equal(performance.getEntriesByName(shared, 'mark').length, 0);
assert.equal(performance.getEntriesByName(other, 'mark').length, 1);
assert.equal(performance.getEntriesByName(shared, 'measure').length, 1);
performance.clearMeasures(shared);
assert.equal(performance.getEntriesByName(shared, 'measure').length, 0);
assert.equal(span.duration, 4);
assert.ok(Number.isFinite(span.duration) && span.duration >= 0);
console.log('namedCleanup=true; entryTypesIndependent=true');
} finally {
performance.clearMarks(shared);
performance.clearMarks(other);
performance.clearMeasures(shared);
}确定输出:
namedCleanup=true; entryTypesIndependent=true
生产审查时,可以把问题写得更具体:这条记录由谁创建,谁消费,谁删除,错误路径是否仍会执行删除。清理时间线只是生命周期的一部分;如果上报队列还在保存完整条目或很大的 detail,对时间线调用清理方法并不能替代队列自己的容量控制。
规范对照:User Timing 的按名称清理规则。
四、观察器异步交付,不要用同步日志猜顺序
观察器的回调不是 measure 返回之前必然执行的同步步骤。这个测试用一个布尔哨兵验证回调已离开当前同步阶段,并让 Promise 只在真实回调通过断言之后完成。这样无需猜测等待多少毫秒才够,也不会把一次计时器延迟当成接口保证。
为检验列表排序,代码先创建起点较晚的区间,再创建起点较早的区间。回调用 getEntries 取出的结果应按 startTime 排列。另建一个 mark 作为干扰项,确认只订阅 measure 时不会混入标记。这里两个测量在同一段同步代码中创建,不能推广成跨多个异步任务永远只回调一次。
文件:04-observer-delivery.mjs。运行方式:node 04-observer-delivery.mjs。
import assert from 'node:assert/strict';
import { performance, PerformanceObserver } from 'node:perf_hooks';
let inSynchronousPhase = true;
let observer;
const delivered = new Promise((resolve, reject) => {
observer = new PerformanceObserver((list) => {
try {
assert.equal(inSynchronousPhase, false);
const entries = list.getEntries();
assert.deepEqual(entries.map((entry) => entry.name), [
'review:observer:early', 'review:observer:late'
]);
for (const entry of entries) {
assert.equal(entry.entryType, 'measure');
assert.ok(Number.isFinite(entry.duration) && entry.duration >= 0);
}
resolve();
} catch (error) {
reject(error);
}
});
});
try {
observer.observe({ entryTypes: ['measure'] });
performance.mark('review:observer:noise');
performance.measure('review:observer:late', { start: 20, end: 25 });
performance.measure('review:observer:early', { start: 10, end: 12 });
inSynchronousPhase = false;
await delivered;
console.log('asynchronousDelivery=true; filteredAndSorted=true');
} finally {
observer.disconnect();
performance.clearMarks('review:observer:noise');
performance.clearMeasures('review:observer:early');
performance.clearMeasures('review:observer:late');
}确定输出:
asynchronousDelivery=true; filteredAndSorted=true
回调里的异常被转给等待中的 Promise,所以测试不会在输出成功之后才冒出未处理错误。生产采集器还应自行限制回调工作量、隔离序列化与网络失败,并在不需要采集时取消订阅。不要仅凭观察器看到了一条记录,就认定远端日志系统已经收到它。
五、takeRecords 取走待交付记录,不负责清理时间线
观察器自己的待交付队列和 performance 可查询的时间线是不同的状态。下面在当前同步阶段内生成标记,立即调用 takeRecords 取走队列,再调用一次确认队列已空。与此同时,按名称查询时间线仍然得到原标记。把这两个检查写在一起,比一句清空缓存更准确。
随后断开观察器,再让出一次事件循环,检查回调没有执行。本例验证的是这次明确的取队列并断开操作,不把 setImmediate 当成等待任意观察器交付的通用屏障。需要正常交付时,应像上一例那样等待自己的完成信号。
文件:05-take-records.mjs。运行方式:node 05-take-records.mjs。
import assert from 'node:assert/strict';
import { setImmediate } from 'node:timers/promises';
import { performance, PerformanceObserver } from 'node:perf_hooks';
const name = 'review:queue:one';
let callbackCount = 0;
const observer = new PerformanceObserver(() => { callbackCount += 1; });
try {
observer.observe({ type: 'mark' });
performance.mark(name);
const records = observer.takeRecords();
assert.equal(records.length, 1);
assert.equal(records[0].name, name);
assert.ok(Number.isFinite(records[0].startTime) && records[0].startTime >= 0);
assert.equal(observer.takeRecords().length, 0);
assert.equal(performance.getEntriesByName(name, 'mark').length, 1);
observer.disconnect();
await setImmediate();
assert.equal(callbackCount, 0);
console.log('observerQueueDrained=true; timelineRetained=true');
} finally {
observer.disconnect();
performance.clearMarks(name);
}确定输出:
observerQueueDrained=true; timelineRetained=true
这对关闭采集器尤其重要:如果业务要求处理最后一批待交付记录,先明确取出的记录由谁处理,再断开订阅。不要把 disconnect 当作自动刷新并上传的操作。队列取出、数据消费、停止订阅和时间线清理应有明确次序,各自的失败也应有可观察的结果。
规范对照:Performance Timeline 的队列取出与断开订阅规则。
六、回看历史要显式选择 buffered
有些 AI 实现会在任务结束后才创建观察器,然后期待收到此前的标记。此时需要明确历史读取意图。这个例子先生成标记,再用单类型配置 type 与 buffered 订阅。历史条目进入观察器队列后,马上清理全局时间线,回调依然应该拿到已排入队列的那条记录。
代码特意选择 type 而不是把 buffered 随手拼进任意配置形式。历史回看依赖订阅时仍然存在的记录,已经提前清掉的标记无法靠这个选项复活。正式系统若需要完整历史,应在自己的存储策略里解决保留与容量问题。
文件:06-buffered-history.mjs。运行方式:node 06-buffered-history.mjs。
import assert from 'node:assert/strict';
import { performance, PerformanceObserver } from 'node:perf_hooks';
const name = 'review:history:ready';
let observer;
performance.mark(name, { startTime: 3 });
const delivered = new Promise((resolve, reject) => {
observer = new PerformanceObserver((list) => {
try {
const entries = list.getEntriesByName(name, 'mark');
assert.equal(entries.length, 1);
assert.equal(entries[0].startTime, 3);
assert.ok(Number.isFinite(entries[0].startTime) && entries[0].startTime >= 0);
assert.equal(performance.getEntriesByName(name, 'mark').length, 0);
resolve();
} catch (error) {
reject(error);
}
});
});
try {
observer.observe({ type: 'mark', buffered: true });
performance.clearMarks(name);
await delivered;
console.log('bufferedHistory=true; queuedAfterClear=true');
} finally {
observer.disconnect();
performance.clearMarks(name);
}确定输出:
bufferedHistory=true; queuedAfterClear=true
这是一条很有价值的代码审查线索:从时间线清除记录,与撤回已经发给观察器队列的通知,不能画等号。若业务在取消操作后禁止继续上报,应有自己的取消状态或采集器关闭协议,而不是只删除一个标记名称后就假定所有后续通知已经消失。
版本实现核对:Node.js v24.19.0 观察器实现,用于核对本文的历史排队与清理组合,不把内部调度细节当成跨版本承诺。
七、detail 是克隆后的载荷,但没有自动冻结
向标记和测量添加 detail 时,可以把它看作当时的上下文快照,但不能把快照误解为不可修改对象。测试先把同一份嵌套载荷交给两个条目,再修改原载荷,验证两个条目仍保留创建时的值。接着修改一个条目中的嵌套对象,确认另一个条目没有跟着改变。
最后故意放入函数,检查结构化克隆失败时的 DataCloneError,以及失败调用没有向可查询时间线加入该名称的条目。这里验证错误类别,不把整段错误文案写进快照;运行时更新可能改变文案,审查目标却没有改变。
文件:07-detail-clone.mjs。运行方式:node 07-detail-clone.mjs。
import assert from 'node:assert/strict';
import { performance } from 'node:perf_hooks';
const markName = 'review:detail:mark';
const measureName = 'review:detail:measure';
const badName = 'review:detail:bad';
try {
const detail = { phase: { state: 'created' } };
const mark = performance.mark(markName, { detail });
const span = performance.measure(measureName, { start: 0, end: 1, detail });
detail.phase.state = 'changed';
assert.notEqual(mark.detail, detail);
assert.notEqual(span.detail, detail);
assert.equal(mark.detail.phase.state, 'created');
assert.equal(span.detail.phase.state, 'created');
mark.detail.phase.state = 'edited';
assert.equal(span.detail.phase.state, 'created');
assert.ok(Number.isFinite(span.duration) && span.duration >= 0);
assert.throws(() => performance.mark(badName, {
detail: { callback() {} }
}), { name: 'DataCloneError' });
assert.equal(performance.getEntriesByName(badName, 'mark').length, 0);
console.log('detailCloned=true; cloneFailureContained=true');
} finally {
performance.clearMarks(markName);
performance.clearMarks(badName);
performance.clearMeasures(measureName);
}确定输出:
detailCloned=true; cloneFailureContained=true
因此,评审建议应同时覆盖载荷大小、可克隆类型和敏感字段。不要把完整请求对象、函数闭包或认证信息随手塞入 detail。克隆只解决对象如何复制,不会替你做脱敏,也不代表多个消费者持有的同一个条目可以任意修改而互不影响。本文只证明独立创建的两个条目各有自己的克隆结果。失败后的查询只覆盖时间线,不代表内部状态全部原子回滚,因此 finally 仍会清理失败名称。
规范对照:User Timing 的 detail 结构化克隆步骤。
八、显式时间戳让边界计算可重复
有时需要回放已经采集的边界,或者测试计算规则而不依赖真实耗时。此时可以为 mark 指定 startTime,并为 measure 指定数值起点、终点,或起点与持续时间。下面三种写法表达同一个区间,断言它们的起点和持续时间一致,但标准输出仍然只报告布尔结论。
这些数值位于同一条性能时间轴,单位是毫秒。它们不是可随意混用的日历时间,也不应该直接混入 Date.now 的纪元读数。测试中的常量是人为构造的输入,只证明区间算术规则,不能被摘出来充当某个真实接口耗时的证据。
文件:08-explicit-timestamps.mjs。运行方式:node 08-explicit-timestamps.mjs。
import assert from 'node:assert/strict';
import { performance } from 'node:perf_hooks';
const startName = 'review:explicit:start';
const endName = 'review:explicit:end';
const names = ['review:explicit:named', 'review:explicit:numeric', 'review:explicit:duration'];
try {
performance.mark(startName, { startTime: 10 });
performance.mark(endName, { startTime: 30 });
const spans = [
performance.measure(names[0], startName, endName),
performance.measure(names[1], { start: 10, end: 30 }),
performance.measure(names[2], { start: 10, duration: 20 })
];
for (const span of spans) {
assert.equal(span.startTime, 10);
assert.equal(span.duration, 20);
assert.ok(Number.isFinite(span.startTime) && span.startTime >= 0);
assert.ok(Number.isFinite(span.duration) && span.duration >= 0);
}
console.log('explicitBoundaries=true; equivalentSpans=true');
} finally {
performance.clearMarks(startName);
performance.clearMarks(endName);
for (const name of names) performance.clearMeasures(name);
}确定输出:
explicitBoundaries=true; equivalentSpans=true
这里的非负条件来自我们构造的有序边界,并不是 measure 会自动纠正任意输入。显式终点早于起点时,持续时间可能为负;如果业务只接受正向区间,就应在进入采集层之前验证顺序。类似地,来自另一进程或另一台机器的数值也需要先说明时钟来源,不能只因字段都叫时间戳就直接相减。
时间轴背景:High Resolution Time 的时间原点;负持续时间边界见 User Timing 的 measure 规则。
九、失败路径也要证明没有成功记录
最后检查两类容易被 AI 忽略的失败:引用一个从未创建的标记,以及同时指定 start、end、duration 三个互相重复约束的选项。前者检查 SyntaxError 名称,后者检查 TypeError 和本次 Node 版本的错误代码。测试不打印异常对象,输出因此不会夹带堆栈路径或版本相关文案。
捕获异常还不够,每次失败之后都查询目标测量名称,确认没有成功条目残留。这样才能把失败分支的可观察结果写完整。错误代码断言是版本范围内的回归检查,换运行时版本时应重新执行,而不是把一次实测扩写成所有 JavaScript 环境的永久承诺。
文件:09-invalid-measures.mjs。运行方式:node 09-invalid-measures.mjs。
import assert from 'node:assert/strict';
import { performance } from 'node:perf_hooks';
const missingName = 'review:invalid:missing';
const overName = 'review:invalid:over';
const absentMark = 'review:invalid:never-created';
try {
assert.equal(performance.getEntriesByName(absentMark, 'mark').length, 0);
assert.throws(() => performance.measure(missingName, {
start: absentMark, end: 10
}), { name: 'SyntaxError' });
assert.equal(performance.getEntriesByName(missingName, 'measure').length, 0);
assert.throws(() => performance.measure(overName, {
start: 1, end: 3, duration: 2
}), { name: 'TypeError', code: 'ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS' });
assert.equal(performance.getEntriesByName(overName, 'measure').length, 0);
console.log('missingMarkRejected=true; invalidOptionsRejected=true');
} finally {
performance.clearMeasures(missingName);
performance.clearMeasures(overName);
}确定输出:
missingMarkRejected=true; invalidOptionsRejected=true
对真实服务而言,埋点失败不一定应该遮盖业务原始异常。可以先确定业务错误优先级,再给观察逻辑安排独立的错误处理路径;但不要直接吞掉所有错误并输出成功,这会让契约测试失去意义。让 AI 修改实现后,成功路径和这两类失败路径都应重新运行。
版本错误代码:Node.js v24.19.0 错误文档。
把审查结论写成可复测的清单
提交审查意见时,可以按边界、状态、交付和失败四组问题组织。边界组说明是否等待真正的任务、是否混用了时间原点;状态组说明标记与测量由谁清理、并发名称是否冲突;交付组说明如何确认观察器处理完成、是否需要历史记录;失败组说明克隆与测量异常如何处理、是否会遮盖业务错误。
请 AI 解释每个断言所保护的错误,而不只要求它生成更多日志。例如,看到非负耗时检查时,应追问这是有序真实时钟的结果,还是业务输入验证后的保证;看到 finally 时,应追问它清理的是自己的条目还是全进程数据。解释与测试互相对应,审查才有可追溯的依据。
最后再做两个独立检查:把文章中的代码块复制出来单独运行,确认没有依赖隐含变量;重复运行包含观察器的示例,确认输出不受随机毫秒值影响。这些检查提高的是教程和契约测试的可信度。要讨论实际性能,还需要单独设计代表性负载、预热方式、采样与统计方案,不能从本文的九行成功结论推导性能排名。

