performance-profiler

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Performance Profiler

性能分析器

Analysis-based performance review. Every recommendation grounded in evidence. 6-mode pipeline: Analyze, Profile, Cache, Benchmark, Regression, Leak-Patterns.
Scope: Performance analysis and recommendations only. NOT for running profilers, executing load tests, infrastructure monitoring, or actual memory leak detection. This skill provides analysis-based guidance, not measurements.
基于分析的性能评审。每一项建议均有证据支撑。 6模式流程:分析、剖析、缓存、基准测试、回归、泄漏模式。
适用范围: 仅提供性能分析与建议。不用于运行分析器、执行负载测试、基础设施监控或实际内存泄漏检测。本技能提供基于分析的指导,而非测量服务。

Canonical Vocabulary

标准术语表

Use these terms exactly throughout all modes:
TermDefinition
complexityBig-O algorithmic classification of a function or code path
hotspotCode region with disproportionate resource consumption (time or memory)
bottleneckSystem constraint limiting overall throughput
profiler outputTextual data from cProfile, py-spy, perf, or similar tools pasted by user
cache strategyEviction policy + write policy + invalidation approach for a caching layer
benchmark skeletonTemplate code for measuring function performance with proper methodology
regression riskLikelihood that a code change degrades performance, scored LOW/MEDIUM/HIGH/CRITICAL
anti-patternKnown performance-harmful code pattern (N+1, unbounded allocation, etc.)
evidenceConcrete proof: AST analysis, profiler data, code pattern match, or external reference
recommendationActionable optimization suggestion with expected impact and trade-offs
flame graphHierarchical visualization of call stack sampling data
wall timeElapsed real time (includes I/O waits) vs CPU time (compute only)
所有模式中需严格使用以下术语:
术语定义
complexity函数或代码路径的大O算法分类
hotspot资源消耗(时间或内存)占比过高的代码区域
bottleneck限制系统整体吞吐量的约束环节
profiler output用户粘贴的来自cProfile、py-spy、perf或类似工具的文本数据
cache strategy缓存层的淘汰策略 + 写入策略 + 失效方案
benchmark skeleton采用规范方法测量函数性能的模板代码
regression risk代码变更导致性能下降的可能性,分为LOW/MEDIUM/HIGH/CRITICAL四个等级
anti-pattern已知的有损性能的代码模式(如N+1查询、无界内存分配等)
evidence具体证据:AST分析、分析器数据、代码模式匹配或外部参考资料
recommendation可落地的优化建议,包含预期影响与权衡点
flame graph调用栈采样数据的层级可视化图表
wall time实际流逝时间(包含I/O等待),区别于CPU时间(仅计算运算时间)

Dispatch

模式调度

$ARGUMENTSMode
analyze <file/function>
Algorithmic complexity analysis, Big-O review
profile <data>
Interpret textual profiler output (cProfile, py-spy, perf)
cache <system>
Caching strategy design (LRU/LFU/TTL/write-through/write-back)
benchmark <code>
Benchmark design and methodology review
regression <diff>
Performance regression risk assessment from code diff
leak-patterns
Common memory leak pattern scan (NOT actual detection)
EmptyShow mode menu with examples for each mode
参数模式
analyze <file/function>
算法复杂度分析、大O评审
profile <data>
解析文本格式的分析器输出(cProfile、py-spy、perf)
cache <system>
缓存策略设计(LRU/LFU/TTL/写穿/写回)
benchmark <code>
基准测试设计与方法评审
regression <diff>
基于代码差异的性能回归风险评估
leak-patterns
常见内存泄漏模式扫描(非实际检测)
空值显示模式菜单及各模式示例

Mode 1: Analyze

模式1:分析

Algorithmic complexity analysis for files or functions.
针对文件或函数的算法复杂度分析。

Analyze Step 1: Scan

分析步骤1:扫描

Run the complexity estimator script:
uv run python skills/performance-profiler/scripts/complexity-estimator.py <path>
Parse JSON output. If script fails, perform manual AST-level analysis.
运行复杂度估算脚本:
uv run python skills/performance-profiler/scripts/complexity-estimator.py <path>
解析JSON输出。若脚本执行失败,则进行手动AST层级分析。

Analyze Step 2: Classify

分析步骤2:分类

For each function in scope:
  1. Identify loop nesting depth, recursion patterns, data structure operations
  2. Map to Big-O classification using
    references/complexity-patterns.md
  3. Score hotspot risk: nesting depth * call frequency * data size sensitivity
  4. Flag functions with O(n^2) or worse in hot paths
对范围内的每个函数:
  1. 识别循环嵌套深度、递归模式、数据结构操作
  2. 使用
    references/complexity-patterns.md
    映射到大O分类
  3. 计算热点风险:嵌套深度 * 调用频率 * 数据规模敏感度
  4. 标记热路径中复杂度为O(n^2)或更差的函数

Analyze Step 3: Report

分析步骤3:报告

Present findings as a table:
FunctionEstimated ComplexityEvidenceHotspot RiskRecommendation
Include trade-off analysis for each recommendation.
以表格形式呈现结果:
函数估算复杂度证据热点风险建议
每条建议需包含权衡分析。

Mode 2: Profile

模式2:剖析

Interpret textual profiler output pasted by the user.
解析用户粘贴的文本格式分析器输出。

Profile Step 1: Parse

剖析步骤1:解析

Run the profile parser script on user-provided data:
uv run python skills/performance-profiler/scripts/profile-parser.py --input <file>
If data is inline, save to temp file first. Parse JSON output.
对用户提供的数据运行分析器解析脚本:
uv run python skills/performance-profiler/scripts/profile-parser.py --input <file>
若数据为内嵌格式,先保存至临时文件。解析JSON输出。

Profile Step 2: Identify Hotspots

剖析步骤2:识别热点

From parsed data:
  1. Rank functions by cumulative time (top 10)
  2. Identify functions with high call count but low per-call time (overhead candidates)
  3. Identify functions with low call count but high per-call time (optimization candidates)
  4. Check for I/O-bound vs CPU-bound patterns (wall time vs CPU time ratio)
从解析后的数据中:
  1. 按累计时间排序函数(取前10名)
  2. 识别调用次数多但单次调用时间短的函数(潜在 overhead 优化候选)
  3. 识别调用次数少但单次调用时间长的函数(优化候选)
  4. 区分I/O密集型与CPU密集型模式(wall time与CPU时间的比值)

Profile Step 3: Recommend

剖析步骤3:建议

For each hotspot, provide:
  • Root cause hypothesis with evidence from the profiler data
  • Optimization approach with expected impact range
  • Trade-offs and risks of the optimization
  • Reference to relevant anti-patterns from
    references/anti-patterns.md
针对每个热点,提供:
  • 基于分析器数据的根因假设
  • 优化方案及预期影响范围
  • 优化的权衡点与风险
  • 引用
    references/anti-patterns.md
    中的相关反模式

Mode 3: Cache

模式3:缓存

Design caching strategies for a described system.
为指定系统设计缓存策略。

Cache Step 1: Understand Access Patterns

缓存步骤1:理解访问模式

Ask about or infer from code:
  1. Read/write ratio
  2. Data freshness requirements (TTL tolerance)
  3. Cache size constraints
  4. Consistency requirements (eventual vs strong)
  5. Eviction pressure (working set vs cache capacity)
询问或从代码中推断:
  1. 读写比例
  2. 数据新鲜度要求(TTL容忍度)
  3. 缓存大小限制
  4. 一致性要求(最终一致性 vs 强一致性)
  5. 淘汰压力(工作集 vs 缓存容量)

Cache Step 2: Design Strategy

缓存步骤2:设计策略

Use
references/caching-strategies.md
decision tree:
FactorLRULFUTTLWrite-ThroughWrite-Back
Read-heavy, stable working setGoodBestOK----
Write-heavy------SafeFast
Strict freshness----BestBestRisky
Memory-constrainedBestGoodOK----
使用
references/caching-strategies.md
中的决策树:
因素LRULFUTTLWrite-ThroughWrite-Back
读密集、稳定工作集良好最佳尚可----
写密集------安全快速
严格新鲜度----最佳最佳有风险
内存受限最佳良好尚可----

Cache Step 3: Specify

缓存步骤3:详细说明

Deliver: eviction policy, write policy, invalidation strategy, warm-up approach, monitoring recommendations. Include capacity planning formula.
提供:淘汰策略、写入策略、失效方案、预热方法、监控建议。包含容量规划公式。

Mode 4: Benchmark

模式4:基准测试

Design benchmarks and review methodology.
设计基准测试并评审方法。

Benchmark Step 1: Generate Skeleton

基准测试步骤1:生成模板

Run the benchmark designer script:
uv run python skills/performance-profiler/scripts/benchmark-designer.py --function <signature> --language <lang>
Parse JSON output for setup code, benchmark code, iterations, warmup.
运行基准测试设计脚本:
uv run python skills/performance-profiler/scripts/benchmark-designer.py --function <signature> --language <lang>
解析JSON输出获取初始化代码、基准测试代码、迭代次数、预热流程。

Benchmark Step 2: Review Methodology

基准测试步骤2:评审方法

Validate against benchmark best practices:
  1. Warmup period sufficient to stabilize JIT/caches
  2. Iteration count provides statistical significance
  3. Measurement excludes setup/teardown overhead
  4. Environment controlled (no interference from other processes)
  5. Results include variance/percentiles, not just mean
对照基准测试最佳实践验证:
  1. 预热时长足够稳定JIT/缓存
  2. 迭代次数具备统计显著性
  3. 测量结果排除初始化/清理开销
  4. 环境受控(无其他进程干扰)
  5. 结果包含方差/百分位数,而非仅平均值

Benchmark Step 3: Deliver

基准测试步骤3:交付

Provide complete benchmark code with methodology notes, expected metrics, and interpretation guide.
提供完整的基准测试代码及方法说明、预期指标、结果解读指南。

Mode 5: Regression

模式5:回归

Assess performance regression risk from a code diff.
基于代码差异评估性能回归风险。

Regression Step 1: Collect Diff

回归步骤1:收集差异

If path provided, read the diff. If git range provided, run
git diff
. Identify changed functions and their call sites.
若提供路径,则读取差异;若提供Git范围,则运行
git diff
。识别变更的函数及其调用位置。

Regression Step 2: Assess Risk

回归步骤2:评估风险

For each changed function:
Risk FactorWeightCheck
Complexity increase3xLoop nesting added, algorithm changed
Hot path change3xFunction called in request/render path
Data structure change2xCollection type or size assumptions changed
I/O pattern change2xNew network/disk calls, removed batching
Memory allocation1xNew allocations in loops, larger buffers
Risk score = sum of (weight * severity). Map to LOW/MEDIUM/HIGH/CRITICAL.
针对每个变更的函数:
风险因素权重检查项
复杂度提升3x添加循环嵌套、算法变更
热路径变更3x函数在请求/渲染路径中被调用
数据结构变更2x集合类型或规模假设变更
I/O模式变更2x新增网络/磁盘调用、移除批处理
内存分配1x循环中新增内存分配、缓冲区扩容
风险得分 = (权重 * 严重程度)之和。映射至LOW/MEDIUM/HIGH/CRITICAL等级。

Regression Step 3: Report

回归步骤3:报告

Present regression risk matrix with:
  • Per-function risk assessment with evidence
  • Aggregate risk score for the diff
  • Recommended benchmark targets before merging
  • Specific measurements to validate (what to profile and where)
呈现回归风险矩阵,包含:
  • 每个函数的风险评估及证据
  • 差异的整体风险得分
  • 合并前建议的基准测试目标
  • 需要验证的具体测量项(分析对象及位置)

Mode 6: Leak-Patterns

模式6:泄漏模式

Scan for common memory leak patterns. Static analysis only -- NOT actual leak detection.
扫描常见内存泄漏模式。仅静态分析——非实际泄漏检测。

Leak Step 1: Scan

泄漏步骤1:扫描

Read target files and check against patterns in
references/leak-patterns.md
:
  • Event listener accumulation without cleanup
  • Closure-captured references preventing GC
  • Growing collections without bounds (unbounded caches, append-only lists)
  • Circular references in reference-counted languages
  • Resource handles not closed (files, connections, cursors)
  • Global state accumulation
读取目标文件,对照
references/leak-patterns.md
中的模式检查:
  • 事件监听器累积未清理
  • 闭包捕获引用导致GC无法回收
  • 无界增长的集合(无界缓存、仅追加列表)
  • 引用计数语言中的循环引用
  • 未关闭的资源句柄(文件、连接、游标)
  • 全局状态累积

Leak Step 2: Classify

泄漏步骤2:分类

For each potential leak pattern found:
PatternLanguageSeverityFalse Positive Risk
针对每个发现的潜在泄漏模式:
模式语言严重程度误报风险

Leak Step 3: Report

泄漏步骤3:报告

Present findings with code citations, explain why each pattern risks leaking, and suggest fixes. Acknowledge that static analysis has high false positive rates -- recommend actual profiling tools for confirmation.
呈现结果,包含代码引用、解释各模式为何存在泄漏风险,并提供修复建议。需说明静态分析误报率较高——建议使用实际分析工具确认。

Scaling Strategy

扩展策略

ScopeStrategy
Single functionDirect analysis, inline report
Single file (< 500 LOC)Script-assisted analysis, structured report
Multiple files / moduleParallel subagents per file, consolidated report
Full codebasePrioritize entry points and hot paths, sample-based analysis
范围策略
单个函数直接分析、内嵌报告
单个文件(<500行代码)脚本辅助分析、结构化报告
多文件/模块每个文件分配并行子Agent、合并报告
完整代码库优先分析入口点与热路径、基于采样的分析

Reference Files

参考文件

Load ONE reference at a time. Do not preload all references into context.
FileContentRead When
references/complexity-patterns.md
Code pattern to Big-O mapping with examplesMode 1 (Analyze)
references/caching-strategies.md
Caching decision tree, eviction policies, trade-offsMode 3 (Cache)
references/anti-patterns.md
Performance anti-patterns catalog (N+1, unbounded alloc, etc.)Mode 2 (Profile), Mode 5 (Regression), Mode 6 (Leak)
references/leak-patterns.md
Memory leak patterns by language (Python, JS, Go, Java)Mode 6 (Leak-Patterns)
references/profiler-guide.md
Profiler output interpretation, flame graph readingMode 2 (Profile)
references/benchmark-methodology.md
Benchmark design best practices, statistical methodsMode 4 (Benchmark)
ScriptWhen to Run
scripts/complexity-estimator.py
Mode 1 — static complexity analysis via AST
scripts/profile-parser.py
Mode 2 — parse cProfile/pstats textual output to JSON
scripts/benchmark-designer.py
Mode 4 — generate benchmark skeleton from function signature
TemplateWhen to Render
templates/dashboard.html
After any mode — inject results JSON into data tag
每次仅加载一个参考文件。请勿预先将所有参考文件加载至上下文。
文件内容加载时机
references/complexity-patterns.md
代码模式与大O映射及示例模式1(分析)
references/caching-strategies.md
缓存决策树、淘汰策略、权衡点模式3(缓存)
references/anti-patterns.md
性能反模式目录(N+1查询、无界分配等)模式2(剖析)、模式5(回归)、模式6(泄漏)
references/leak-patterns.md
各语言内存泄漏模式(Python、JS、Go、Java)模式6(泄漏模式)
references/profiler-guide.md
分析器输出解读、火焰图阅读指南模式2(剖析)
references/benchmark-methodology.md
基准测试设计最佳实践、统计方法模式4(基准测试)
脚本运行时机
scripts/complexity-estimator.py
模式1 — 通过AST进行静态复杂度分析
scripts/profile-parser.py
模式2 — 将cProfile/pstats文本输出解析为JSON
scripts/benchmark-designer.py
模式4 — 根据函数签名生成基准测试模板
模板渲染时机
templates/dashboard.html
任意模式完成后 — 将结果JSON注入数据标签

Data Files

数据文件

FileContent
data/complexity-patterns.json
Code pattern to Big-O mapping (machine-readable)
data/caching-strategies.json
Caching decision tree (machine-readable)
data/anti-patterns.json
Performance anti-patterns catalog (machine-readable)
文件内容
data/complexity-patterns.json
代码模式与大O映射(机器可读)
data/caching-strategies.json
缓存决策树(机器可读)
data/anti-patterns.json
性能反模式目录(机器可读)

Critical Rules

核心规则

  1. Never claim to measure performance — this skill provides analysis, not measurement
  2. Every recommendation must include trade-offs — no "just do X" advice
  3. Always acknowledge uncertainty in complexity estimates — static analysis has limits
  4. Never recommend premature optimization — confirm the code is actually on a hot path first
  5. Profiler output interpretation must cite specific data points, not general principles
  6. Cache strategy recommendations must address invalidation — "cache invalidation is hard" is not a strategy
  7. Benchmark designs must include warmup, statistical significance, and variance reporting
  8. Regression risk assessment must trace to specific code changes, not general concerns
  9. Leak pattern scanning is pattern-matching only — always recommend actual profiling for confirmation
  10. Load ONE reference file at a time — do not preload all references into context
  11. Present findings with evidence before suggesting fixes (approval gate)
  12. Anti-pattern findings require code citation
    [file:line]
    — no generic warnings
  1. 绝不声称能测量性能——本技能仅提供分析,不提供测量服务
  2. 每条建议必须包含权衡点——禁止仅给出“直接做X”的建议
  3. 始终承认复杂度估算的不确定性——静态分析存在局限性
  4. 绝不推荐过早优化——先确认代码确实处于热路径
  5. 分析器输出解读必须引用具体数据点,而非泛泛而谈
  6. 缓存策略建议必须解决失效问题——“缓存失效很难”不是有效策略
  7. 基准测试设计必须包含预热、统计显著性及方差报告
  8. 回归风险评估必须追溯至具体代码变更,而非笼统担忧
  9. 泄漏模式扫描仅为模式匹配——始终建议使用实际分析工具确认
  10. 每次仅加载一个参考文件——请勿预先将所有参考文件加载至上下文
  11. 提出修复建议前需先呈现带证据的发现(审批门槛)
  12. 反模式发现需包含代码引用
    [file:line]
    ——禁止通用警告