如何在Node.js中统计函数执行耗时?求console.time之外的方案
Node.js 脚本函数执行耗时的统计方案
关于 --time 参数的可用性
Node.js 确实支持 --time(简写 -t)命令行参数,它会在脚本执行完毕后输出整个脚本的总生命周期耗时,包含启动、代码运行的全部时间。如果用 node --watch --time test.js 运行脚本,每次文件变更触发重启后,控制台会输出类似内容:
[watch] build succeeded, waiting for file changes... real 0m0.123s user 0m0.045s sys 0m0.012s
real:脚本从启动到结束的实际耗时user:CPU 在用户态消耗的时间sys:CPU 在内核态消耗的时间
但要注意,这个参数统计的是整个脚本的耗时,无法精准定位单个函数的执行时间,若只想统计 extract 函数的耗时,需要用以下方法。
除 console.time 外的其他实现方式
1. 用 process.hrtime() 手动计算
process.hrtime() 提供纳秒级高精度时间戳,适合精准统计代码块耗时:
let a = ... function extract(input) { ..... } // 记录开始时间 const start = process.hrtime(); const ext = extract(a); // 计算耗时 const [seconds, nanoseconds] = process.hrtime(start); const durationMs = seconds * 1000 + nanoseconds / 1e6; console.log(ext); console.log(`extract 函数耗时: ${durationMs.toFixed(3)}ms`);
2. 使用 performance.now()
Node.js 支持浏览器兼容的 performance.now(),返回带小数的毫秒级时间(精确到微秒):
let a = ... function extract(input) { ..... } const start = performance.now(); const ext = extract(a); const durationMs = performance.now() - start; console.log(ext); console.log(`extract 函数耗时: ${durationMs.toFixed(3)}ms`);
3. console.profile 配合 Chrome DevTools 做深度分析
如果需要查看函数内部子调用的耗时细节,可以用调试工具:
- 带调试参数运行脚本:
node --watch --inspect test.js - 打开 Chrome 浏览器访问
chrome://inspect,找到对应 Node 进程点击「Inspect」 - 在代码中添加性能标记:
console.profile('extract-profile'); const ext = extract(a); console.profileEnd('extract-profile');
- 在 DevTools 的「Performance」面板中查看详细的函数调用耗时和性能数据
总结
- 统计整个脚本耗时:使用
--time参数 - 精准统计单个函数耗时:优先选
performance.now()或process.hrtime() - 深度性能分析:用
console.profile配合 Chrome DevTools
内容的提问来源于stack exchange,提问作者Paul
相关产品推荐
相关产品推荐

