feat(perf): 添加 TypeScript 层性能埋点#8
CodeBuddy Code
本次提交为 TypeScript 代码层面添加了完整的性能埋点能力,支持微秒级耗时统计和结构化日志输出。
src/utils/performance.ts
核心功能:
process.hrtime.bigint()
text
json
createPerformanceTracker()
measureTimeAsync()
performanceCollector
API 示例:
const perf = createPerformanceTracker("配置加载"); perf.start(); // ... 执行代码 perf.mark("解析JSON"); perf.mark("验证配置"); perf.end(); // 自动输出结构化日志
src/app.ts
env_parse
image_extract
vision_call
prompt_build
openclaw_call
comment_post
src/tools/cnb.ts
cnb_issue_comment
cnb_pull_comment
tsconfig.json
target
es2018
ES2020
[perf] {stage} | total={duration}μs ({duration}ms) | {marks} | metadata={json}
示例输出:
[perf] image_extract | total=15234μs (15.23ms) | extract=5230μs,convert=8920μs [perf] openclaw_call | total=5234567μs (5234.57ms) [perf] ===== 性能统计汇总 ===== [perf] 总阶段数: 6 [perf] 总耗时: 5345678μs (5345.68ms) [perf] 各阶段耗时: - env_parse: 123μs (0%) - image_extract: 15234μs (0%) - vision_call: 1234567μs (23%) - prompt_build: 4567μs (0%) - openclaw_call: 5234567μs (98%) - comment_post: 34567μs (1%) [perf] ==========================
资中工程师
资深工程师
OpenClaw
问题: 性能追踪器未正确结束
当 userQuestion 为空时,函数提前 return,但 mainPerf.end() 没有被调用。这会导致性能追踪数据不完整。
userQuestion
return
mainPerf.end()
建议: 在提前返回前调用 mainPerf.end():
if (!userQuestion.trim()) { console.log("[main] 用户输入为空,跳过"); mainPerf.end(); return; }
问题: 异常分支下性能追踪器未结束
在抛出异常之前没有调用 perf.end(),导致性能数据不完整。同样的问题存在于第 76-77 行的 !CNB_TOKEN 检查。
perf.end()
!CNB_TOKEN
建议: 使用 try-finally 模式确保追踪器总是被结束:
try-finally
export async function postCNBComment(options: PostCommentOptions): Promise<CommentResponse> { const perf = createPerformanceTracker("cnb_issue_comment", { silent: true }); perf.start(); try { // ... 业务逻辑 return result; } catch (error) { throw error; } finally { perf.end(); } }
问题: 使用非空断言操作符 ! 存在运行时风险
!
durationFromStart 和 durationFromPrevious 在接口中定义为可选属性,但此处直接使用 ! 断言非空。虽然在 end() 方法中这些值理论上总是存在,但使用非空断言绕过了类型检查,如果逻辑变更可能引入运行时错误。
durationFromStart
durationFromPrevious
end()
建议:
marks: marks.map((m) => ({ name: m.name, durationUs: formatDuration(m.durationFromStart ?? 0n), durationFromPreviousUs: formatDuration(m.durationFromPrevious ?? 0n), percentage: m.durationFromStart ? Number((m.durationFromStart * 100n) / totalDurationNs) : 0 })),
评审结果: 通过
代码质量良好,未发现明显问题。
优点:
cnb.ts
silent
建议(可选):
PerformanceCollector
CodeBuddy Code
关联 Issue
变更摘要
本次提交为 TypeScript 代码层面添加了完整的性能埋点能力,支持微秒级耗时统计和结构化日志输出。
新增文件
src/utils/performance.ts- 性能埋点工具模块核心功能:
process.hrtime.bigint()实现高精度计时text和json两种格式createPerformanceTracker()APImeasureTimeAsync()便捷函数performanceCollector汇总多次测量API 示例:
const perf = createPerformanceTracker("配置加载"); perf.start(); // ... 执行代码 perf.mark("解析JSON"); perf.mark("验证配置"); perf.end(); // 自动输出结构化日志修改文件
src/app.ts- 关键路径埋点env_parseimage_extractvision_callprompt_buildopenclaw_callcomment_postsrc/tools/cnb.ts- API 调用埋点cnb_issue_commentcnb_pull_commenttsconfig.json- 编译目标升级target从es2018升级到ES2020,以支持 BigInt 字面量语法日志格式
示例输出:
测试
下一步