| name | perf-tune |
| description | Professional CPU performance optimization skill covering 10 performance dimensions.
This skill should be used when profiling, benchmarking, or optimizing code
for CPU performance on x86, ARM, and RISC-V architectures.
Supports C, C++, Rust, Go, and Python (via native extensions).
Covers cache-friendly data structures, vectorization, loop optimizations,
branchless programming, machine code layout (PGO/BOLT), multithreading
tuning, and system-level optimizations (NUMA, huge pages).
Includes TMA (Top-Down Microarchitecture Analysis) workflow and
10-dimension performance coverage matrix.
|
| tools | ["Read","Grep","Glob","Bash","Task","LSP"] |
| priority | high |
| file_patterns | ["**/*.c","**/*.cpp","**/*.cc","**/*.cxx","**/*.h","**/*.hpp","**/*.rs","**/*.go","**/*.py","**/*.pyx","**/*.pxd","**/*.s","**/*.S","**/*.asm","**/CMakeLists.txt","**/Makefile","**/Cargo.toml","**/go.mod"] |
| exclude_patterns | ["**/node_modules/**","**/vendor/**","**/dist/**","**/build/**","**/.git/**","**/target/**","**/__pycache__/**","**/third_party/**"] |
Perf-Tune Skill
Professional CPU Performance Optimization Skill
Supported Modes: quick / standard / deep
When to Use This Skill
This skill should be used when:
- User requests performance optimization or CPU profiling
- User asks to speed up code, reduce latency, or improve throughput
- User mentions /perf or /tune
- User wants to analyze a performance bottleneck or profile hot code
- User needs cache optimization, vectorization, multithreading tuning
- User asks about PMU counters, perf, VTune, or TMA
Trigger phrases:
- "Optimize this code"
- "Profile this program"
- "Find the bottleneck"
- "Make this faster"
- "/perf", "/tune", "/optimize"
Quick Reference
Scan Modes
| Mode | Use Case | Scope |
|---|
| Quick | Hotspot identification, single-function profiling | PMU counters, top bottlenecks, quick wins |
| Standard | Module-level optimization | Full TMA analysis, multi-dimension coverage, 1-2 rounds |
| Deep | Whole-program optimization, release preparation | All 10 dimensions, iterative refinement, multi-agent, 2-3 rounds |
Core Workflow
1. Reconnaissance → Identify language, build system, workload characteristics
2. Measurement → Profile with perf/VTune, collect PMU counters, identify bottleneck category
3. TMA Diagnosis → Apply Top-Down Microarchitecture Analysis to narrow root cause
4. Optimization → Select and apply techniques matched to bottleneck type
5. Verification → Re-measure, confirm improvement, check correctness (tests pass)
6. Report → Document before/after metrics, techniques applied, tradeoffs
Quick Profiling Commands
perf stat -e cycles,instructions,cache-references,cache-misses,branches,branch-misses ./program
perf record -g ./program && perf script | stackcollapse-perf.pl | flamegraph.pl > flame.svg
perf stat --topdown -a ./program
See: references/core/measurement.md, references/tools/linux_perf.md
Execution Controller (Mandatory Path)
⚠️ The following steps are mandatory for optimization execution, not suggestions.
Each step has required outputs; subsequent steps depend on previous outputs. No output = visible gap to the user.
Step 1: Mode Determination
Determine optimization mode based on user instructions:
| User Instruction Keywords | Mode |
|---|
| "quick analysis" "quick" "hotspot" "where's the bottleneck" | quick |
| "optimize" "speed up" "profile" (no special instructions) | standard |
| "deep optimization" "deep" "comprehensive optimization" "release prep" | deep |
| Cannot determine | Ask the user, do not assume |
Anti-Downgrade Rule: The mode specified by the user must not be downgraded. Large code size is not a reason for downgrade — it is a reason to enable Multi-Agent. Downgrade requires explicit user confirmation.
Required Output:
[MODE] {quick|standard|deep}
Step 2: Document Loading
Load required documents by mode (actually read with the Read tool, not "know this file exists"):
| Mode | Required Documents to Read |
|---|
| quick | Current SKILL.md already loaded, no additional documents needed |
| standard | + references/checklists/coverage_matrix.md |
| deep | + agent.md (read completely, cannot skip) + coverage_matrix.md |
In deep mode, agent.md is mandatory — the Step 4 execution plan template contains fields unique to agent.md (dimension weights, Agent split templates, gate conditions, execution state machine).
Required Output:
[LOADED] {List of actually Read documents, with line counts}
Step 3: Reconnaissance
Profile the target project for performance characteristics.
Required Output:
[RECON]
Project Size: {X files, Y lines of code}
Language/Build System: {C++/CMake | Rust/Cargo | Go | Python/Cython}
Architecture: {x86-64 | ARM64 | RISC-V}
Key Modules: {Identified computation hotspot modules}
Workload Type: {compute-bound | memory-bound | IO-bound | latency-sensitive | throughput-oriented}
Step 4: Measurement → Must Actually Run
Run performance measurements on the target code. Quick mode can be skipped (static analysis only), standard/deep modes must execute.
Quick Mode (static analysis, no actual measurements):
[MEASURE] SKIPPED — Quick mode, estimating bottlenecks via static analysis
Standard/Deep Mode (actual measurements required):
[MEASURE]
Tool: {perf | VTune | Instruments | cargo bench | go test -bench}
PMU Data:
IPC: {instructions per cycle}
Branch Mispredict Rate: {X%}
Cache Miss Rate: {L1 / L2 / L3}
TMA Level 1: {Frontend Bound X% | Backend Bound X% | Bad Speculation X% | Retiring X%}
Bottleneck Category: {Frontend | Backend:Memory | Backend:Core | Bad Speculation}
Step 5: Execution Plan → STOP
Generate an execution plan based on Step 3-4 outputs. Pause after output, wait for user confirmation before continuing.
Quick/Standard Template:
[PLAN]
Mode: {mode}
Bottleneck Category: {from Step 4}
Optimization Dimensions: {P1-P10 dimensions planned to cover}
Loaded Documents: {from Step 2}
Deep Mode Template (all fields required — source document noted):
[PLAN]
Mode: deep
Project Size: {from Step 3}
Language/Architecture: {from Step 3}
Bottleneck Category: {from Step 4}
Dimension Weights: {from agent.md state machine → bottleneck category dimension weights, e.g., Memory-Bound: P1(++), P7(+), P4(+)}
Agent Plan: {from agent.md Agent templates → each Agent's assigned dimensions and max_turns}
Agent Count: {from agent.md sizing advice → Small(<10K lines) 2-3, Medium(10K-100K) 3-5, Large(>100K) 5-7}
P1+P7 Coverage Strategy: {If Backend:Memory bottleneck → P1+P7 must be checked, Memory Agent must cover cache + data layout + prefetch + bandwidth}
Round Plan: R1 breadth optimization → R1 evaluation → R2 incremental depth (as needed)
Gate Conditions: PHASE_1_RECON → PHASE_2_MEASURE → ROUND_N_RUNNING → ROUND_N_EVALUATION → REPORT
Estimated Total Turns: {AgentCount × max_turns}
Loaded Documents: {from Step 2}
⚠️ STOP — Pause after outputting the execution plan. Wait for user confirmation before starting optimization.
Step 6: Execution
After user confirmation, execute according to the plan and loaded documents:
- quick: Identify hotspot patterns, provide targeted recommendations, output directly
- standard: Execute Phase 1→5 in order
- deep: Follow agent.md execution state machine strictly
- Launch Multi-Agent in parallel (per the Agent plan confirmed in Step 5)
- Adhere to each State's gate conditions
- Run test suite after each modification to verify correctness
Step 7: Verification Gate
Verify before generating report:
| Prerequisite | quick | standard | deep |
|---|
| Bottleneck category identified | ✅ | ✅ | ✅ |
| P1-P10 coverage marking (✅ covered / ⚠️ shallow / ❌ uncovered) | — | ✅ | ✅ |
| All optimization modifications pass test suite | ✅ | ✅ | ✅ |
| Before/After performance comparison data | — | ✅ | ✅ |
| All Agents completed or timeout noted | — | — | ✅ |
| Round evaluation passed | — | — | ✅ |
Prerequisites not met → do not generate final report.
Anti-Hallucination Rules (MUST FOLLOW)
⚠️ Every performance claim MUST be based on actual measurement or code analysis
✗ Do NOT guess performance characteristics without profiling data
✗ Do NOT fabricate benchmark numbers
✗ Do NOT claim an optimization improves performance without measurement evidence
✗ Do NOT recommend changes based on "common knowledge" without checking if they apply
✓ MUST verify code compiles after changes
✓ MUST run existing test suite after each optimization
✓ MUST use actual PMU counter data when available
✓ MUST profile before AND after each optimization
✓ MUST report if optimization had no effect or negative effect
Core principle: Better to admit insufficient data than fabricate performance claims.
Anti-Confirmation-Bias Rules (MUST FOLLOW)
⚠️ Optimization MUST be data-driven, NOT intuition-driven
✗ Do NOT say "loop unrolling is always better"
✗ Do NOT assume a technique works because it worked elsewhere
✗ Do NOT skip measurement because "the optimization is obvious"
✓ MUST measure before optimizing (baseline)
✓ MUST measure after each optimization (validation)
✓ MUST consider that the compiler may already apply the optimization
✓ MUST check compiler optimization reports before manually intervening
✓ MUST accept when an optimization has no effect — and report it
Core principle: Let the hardware counters decide, not your intuition.
Performance Dimension Coverage (10-Dimension Matrix)
Layer 1: coverage_matrix.md — Load after Phase 2 completion, verify 10-dimension performance coverage
Layer 2: Domain-specific references — load corresponding optimization technique files on demand for uncovered dimensions
| # | Dimension | Key Questions | Book Chapter |
|---|
| P1 | Memory Access | Cache hit rate? Is data layout cache-friendly? Need prefetching? | Ch8 |
| P2 | Computation | Is the hot loop vectorized? Inlining sufficient? Can loops be optimized? | Ch9 |
| P3 | Branch Prediction | Branch prediction accuracy? Can it be branchless? Is the critical branch predictable? | Ch10 |
| P4 | Front-End / Code Layout | Frontend bottleneck? Code layout optimized? ITLB misses? Need PGO/BOLT? | Ch11 |
| P5 | Multithreading | Parallel scalability? False sharing? Lock contention? Thread affinity? | Ch13 |
| P6 | Data Dependencies | How many serial dependencies on the critical path? ILP utilization? | Ch9.1 |
| P7 | Memory Bandwidth | Bandwidth saturation? Data compression? Data flow optimization? | Ch8.4 |
| P8 | System Tuning | NUMA configuration? Huge pages? Kernel parameters? | Ch12 |
| P9 | Compiler Optimizations | Compiler flags? PGO/LTO? Inlining decisions? Pragma hints? | Ch11.7 |
| P10 | I/O & External | I/O waits? System call overhead? External dependency latency? | Ch12.1 |
Module Reference
Core Modules (Load First)
| Module | Path | Purpose |
|---|
| Performance Measurement | references/core/measurement.md | Profiling methodology, noise reduction, benchmarking |
| CPU Microarchitecture | references/core/microarchitecture.md | Pipeline, ILP, memory hierarchy, SIMD fundamentals |
| Terminology & Metrics | references/core/terminology.md | IPC, CPI, UOPs, cache misses, branch mispredicts |
| Analysis Approaches | references/core/analysis_approaches.md | Sampling, tracing, instrumentation, Roofline, static analysis |
| TMA Workflow | references/core/tma_workflow.md | Top-Down Microarchitecture Analysis step-by-step |
| PMU & CPU Features | references/core/cpu_features.md | PMU counters, LBR, PEBS, PT, Top-Down |
Tool Guides (Load by Toolchain)
| Tool | Module | When to Load |
|---|
| Linux perf | references/tools/linux_perf.md | Linux/x86 projects |
| Intel VTune | references/tools/vtune.md | Intel CPU, deep analysis |
| cargo bench | references/tools/cargo_bench.md | Rust projects |
| go test -bench | references/tools/go_bench.md | Go projects |
Optimization Modules (Load by Bottleneck)
| Bottleneck | Module | Techniques |
|---|
| Cache Misses | references/optimization/memory/cache_friendly.md | Data layout, struct packing, sequential access |
| DTLB Misses | references/optimization/memory/dtlb.md | Huge pages, page walk reduction |
| Memory Prefetching | references/optimization/memory/prefetching.md | Software/hardware prefetch |
| Memory Bandwidth | references/optimization/memory/bandwidth.md | Compression, streaming stores, NT loads |
| Vectorization | references/optimization/computation/vectorization.md | Auto-vec, intrinsics, SIMD |
| Loop Optimization | references/optimization/computation/loops.md | Unroll, fusion, interchange, distribution |
| Inlining | references/optimization/computation/inlining.md | Manual inline, LTO, always_inline |
| Data Dependencies | references/optimization/computation/dependencies.md | Critical path, ILP, instruction scheduling |
| Branch Prediction | references/optimization/branch_prediction/branchless.md | Lookup tables, predication, branch hints |
| Code Layout | references/optimization/code_layout/basic_blocks.md | BB placement, alignment, function splitting |
| PGO | references/optimization/code_layout/pgo.md | Profile-Guided Optimization, BOLT, Propeller |
| ITLB | references/optimization/code_layout/itlb.md | Huge pages for code, code footprint reduction |
| Multithreading | references/optimization/multithreading/scaling.md | Scaling analysis, parallel efficiency, false sharing |
| System Tuning | references/optimization/other_tuning/system.md | NUMA, huge pages, kernel tuning |
| Compiler Flags | references/optimization/other_tuning/compiler.md | -O3, -march, LTO, PGO flags |
Language Modules (Load by Project Language)
| Language | Module | Key Patterns |
|---|
| C/C++ | references/languages/cpp.md | Compiler intrinsics, restrict, alignas, [[likely]] |
| Rust | references/languages/rust.md | repr(align), target_feature, unsafe SIMD, compile flags |
| Go | references/languages/go.md | Escape analysis, sync.Pool, compiler flags |
| Python | references/languages/python.md | Cython, PyPy, NumPy vectorization, native extensions |
Tool Priority Strategy
Priority 1: Hardware Profilers (if available)
├─ perf stat/record/report # Linux perf — universal PMU access
├─ VTune Profiler # Intel — deepest microarchitectural insight
├─ Apple Instruments # macOS — Time Profiler, Allocations
└─ AMD uProf # AMD — Zen-specific analysis
Priority 2: Language/Toolchain Profilers (always check)
├─ cargo bench + perf # Rust — benchmark harness + PMU
├─ go test -bench -benchmem # Go — built-in benchmarking
├─ valgrind --tool=cachegrind # Cache simulation (slow but portable)
└─ llvm-mca / uiCA # Static microarchitectural analysis
Priority 3: Compiler Reports
├─ -Rpass=loop-vectorize # LLVM optimization remarks
├─ -fopt-info-vec # GCC vectorization report
└─ -ftime-report # Compile-time optimization statistics
Priority 4: Verification
├─ Test suite (must pass) # Correctness gate
├─ Benchmark suite # Performance regression detection
└─ Before/After comparison # Evidence of improvement
Detailed Documentation
For complete optimization methodology, bottleneck diagnosis, and technique reference, see:
- Full Workflow:
agent.md - Complete optimization process and multi-agent orchestration
- Measurement Details:
references/core/measurement.md - Noise reduction, benchmarking methodology
- TMA Deep Dive:
references/core/tma_workflow.md - Step-by-step Top-Down Analysis
- Optimization Techniques:
references/optimization/ - Per-bottleneck technique guides
- Language Patterns:
references/languages/ - Language-specific optimization idioms
- Tool Guides:
references/tools/ - profiler and benchmarking tool specific guides
v1.0 (Initial Release)
- 10-dimension performance coverage matrix (P1-P10)
- Top-Down Microarchitecture Analysis (TMA) workflow
- Multi-Agent optimization framework (Memory Agent, Computation Agent, Branch Agent, Layout Agent, Concurrency Agent)
- 100+ concrete optimization techniques based on perf-book
- Supports C/C++, Rust, Go, Python
- Linux perf / Intel VTune / Apple Instruments integration guide