← 中文资源

简体中文版本

console.time 与 console.count 结构化调试输出

console.time/timeEnd 用同名标签配对计时,timeLog 中途打点;console.count 确定性地统计标签触发次数。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

spin: 2.345ms
spin: 6.448ms
total: 19999900000
hits: 1
hits: 2
miss: 1
hits: 3
hits: 1

实现说明

重复被限制在 for (let i = 0; i < 200_000; i++) 里——其余代码按顺序各跑一遍。 各个操作都建立在顶层绑定之上:total。

使用要点

  • 跑完文件,输出里会留下标记——spin、total:、hits。

常见问题

除了语言运行时还需要什么准备?

什么都不需要——语言运行时是唯一要求。 跨调用保留的状态放在这些顶层绑定里:total。

核心语句

console.timeLog("spin"); // 中途打点,计时继续
console.timeEnd("spin"); // 停表并输出
console.log("total:", total);
console.countReset("hits");
console.count("hits");

代码示例

// console.time/timeEnd bracket one labeled span; timeLog logs mid-span checkpoints
console.time("spin");
let total = 0;
for (let i = 0; i < 200_000; i++) {
  total += i;
}
console.timeLog("spin"); // 中途打点,计时继续
console.timeEnd("spin"); // 停表并输出
console.log("total:", total);

// console.count 数同名标签的调用次数:确定性输出
console.count("hits");
console.count("hits");
console.count("miss");
console.count("hits");
console.countReset("hits");
console.count("hits");