如何计算JavaScript中异步方法的执行时间?
统计Node.js异步方法dbFetching执行耗时的方案
- 方案1:业务代码内直接打点统计(最准确)
你最初的写法逻辑是正确的,直接在异步调用前后埋点,不会包含其他逻辑的耗时开销。如果需要更高精度的统计,可以用Node.js内置的performanceAPI,它提供微秒级的时间分辨率,也不受系统时间调整的影响:
const { performance } = require('perf_hooks'); // 原dbFetching调用位置 const start = performance.now(); await dbFetching(); const end = performance.now(); console.log(`dbFetching 执行耗时:${(end - start).toFixed(2)} 毫秒`);
如果需要排除单次请求的网络、数据库波动影响,可以多次调用取平均值:
const { performance } = require('perf_hooks'); const RUN_TIMES = 10; let totalCost = 0; for(let i=0; i<RUN_TIMES; i++){ const start = performance.now(); await dbFetching(); totalCost += performance.now() - start; } console.log(`dbFetching 平均执行耗时:${(totalCost/RUN_TIMES).toFixed(2)} 毫秒`);
- 方案2:无侵入统计(不修改原业务代码)
如果不想改动原s3-glacier.js的代码,你可以单独写一个统计脚本,导入原文件的dbFetching方法后执行统计:
// measure.js const { performance } = require('perf_hooks'); const { dbFetching } = require('./s3-glacier.js'); (async () => { const start = performance.now(); await dbFetching(); const cost = (performance.now() - start).toFixed(2); console.log(`dbFetching 执行耗时:${cost} 毫秒`); process.exit(0); })();
编写完成后执行node measure.js即可得到耗时。如果不想额外创建js文件,也可以直接在shell中通过node -e直接执行统计逻辑:
node -e " const { performance } = require('perf_hooks'); const { dbFetching } = require('./s3-glacier.js'); (async () => { const start = performance.now(); await dbFetching(); console.log('dbFetching执行耗时:' + (performance.now() - start).toFixed(2) + '毫秒'); })(); "
如果原文件没有对外导出dbFetching方法,可临时在原文件中添加导出逻辑,或者直接使用方案1在原调用位置埋点。
- 注意事项
你之前用shell统计整个Node.js进程执行时长的方式误差较大,该时长包含了Node进程启动、代码加载编译、其他业务逻辑执行的额外开销,仅适合整个文件只有dbFetching一个耗时操作的场景。
内容的提问来源于stack exchange,提问作者ahkam
相关产品推荐
相关产品推荐

