--- name: profiling-analysis description: Profile code performance — statistical profilers (perf, samply, flamegraph), hardware counters, benchmark analysis. Use when measuring optimization impact or validating that a change actually improved performance. license: MIT --- ## What I Do Guide performance investigation using profiling tools and hardware counters. Use when investigating why code is slow or validating optimization impact. --- ## The Profiling Mindset ### Why Profile? > "If you haven't measured, you haven't optimized." - Measure actual behavior, not assumed behavior - Find the real bottleneck, not where you think it is - Validate that optimizations actually worked ### Rule of Thumb **Don't optimize what you haven't profiled.** Profile → Optimize → Profile again to verify. --- ## Profiling Tools ### Linux: `perf` The standard Linux profiling tool: ```bash # Basic CPU profiling perf stat -e cycles,instructions,branches,branch-misses ./program # Profile with call graph perf record -g ./program perf report # Hardware counters perf stat -e cache-references,cache-misses,branch-misses ./program # Top hotspots perf top -G ``` ### Key Hardware Events | Event | Description | | ------------------ | ------------------------- | | `cycles` | CPU cycles | | `instructions` | Instructions retired | | `branches` | Branch instructions | | `branch-misses` | Mispredicted branches | | `cache-references` | L1/L2/L3 cache references | | `cache-misses` | Cache misses | | `cpu-migrations` | CPU core migrations | ### Flame Graphs ```bash # Install perf-tools git clone https://github.com/brendangregg/flamegraph.git # Generate flame graph perf record -F 99 -g ./program perf script | ./flamegraph/stackcollapse-perf.pl | ./flamegraph/flamegraph.pl > flame.svg ``` --- ## Identifying Bottlenecks ### CPU-Bound vs Memory-Bound **CPU-Bound signs:** - High `cycles` / low `cache-misses` - Instructions per cycle (IPC) > 1.0 - High CPU utilization **Memory-Bound signs:** - High `cache-misses` relative to `cache-references` - Low IPC (< 1.0) - Memory bandwidth saturation ### Roofline Model ``` Performance = min(Peak FLOPS, Peak Memory Bandwidth × Arithmetic Intensity) Arithmetic Intensity = FLOPs / Bytes Accessed ``` If your code hits the memory roof, optimizing compute won't help. If it hits the compute roof, optimizing memory won't help. --- ## Microbenchmarking ### Statistical Rigor Single measurements are meaningless. Always: 1. **Warm up runs** - JIT compilation, cache warming 2. **Multiple runs** - Minimum 10-30 iterations 3. **Discard outliers** - Remove min/max or use median 4. **Check variance** - High variance = unstable results ### Rust Benchmarking ```rust use criterion::{criterion_group, criterion_main, Criterion, black_box}; fn fibonacci(n: u64) -> u64 { match n { 0 => 1, 1 => 1, _ => fibonacci(n - 1) + fibonacci(n - 2), } } fn bench_fib(c: &mut Criterion) { c.bench_function("fib 20", |b| { b.iter(|| fibonacci(black_box(20))) }); } criterion_group!(benches, bench_fib); criterion_main!(benches); ``` ```bash cargo bench cargo bench -- --plotting-backend terminal ``` ### C/C++ Benchmarking ```c #include static void BM_StringCreation(benchmark::State& state) { for (auto _ : state) std::string empty_string; } BENCHMARK(BM_StringCreation); BENCHMARK_MAIN(); ``` ```bash # Build with optimizations clang -O3 -std=c++17 -march=native -benchmark.cpp -o bench ./bench --benchmark_min_time=3 ``` --- ## Cache Analysis ### Cache Miss Rates ```bash # L1/L2/L3 cache misses perf stat -e cache-references,cache-misses,L1-dcache-load-misses,LLC-load-misses ./program ``` **Good rates:** - L1 miss rate: < 5% - LLC miss rate: < 10% ### Cache Hierarchy Effects ``` L1 Cache: ~32 KB, ~1 ns latency L2 Cache: ~256 KB, ~4 ns latency L3 Cache: ~8 MB, ~15 ns latency RAM: ~GB, ~100 ns latency ``` **10x latency gap** between L1 and RAM means cache misses are expensive. ### Cache Access Patterns **Bad: Strided access** ```c // Accesses every 4096 bytes = cache line torture for (int i = 0; i < n; i += 512) sum += a[i]; ``` **Good: Sequential access** ```c // Sequential = prefetcher works for (int i = 0; i < n; i++) sum += a[i]; ``` --- ## Branch Prediction Analysis ### Misprediction Rates ```bash perf stat -e branches,branch-misses ./program ``` **Good rates:** - < 1% for predictable branches - < 5% for semi-predictable - 10% = consider branchless ### Signs of Branch Mispredictions - High `branch-misses` / `branches` ratio - Code with many if-else in hot paths - Data-dependent branching ### Branchless When - Branch is data-dependent (input decides taken/not-taken) - Branch is in tight loop - Branch is unpredictable --- ## Memory Bandwidth ### Measuring Bandwidth ```bash # STREAM benchmark alternative - simple copy perf stat -e mem_load_retired.l3_hit,mem_load_retired.l3_miss ./program ``` ### Roofline: Know Your Limits ``` DDR4-3200: ~25 GB/s per channel AVX-512 memory bandwidth: ~100 GB/s ``` If your code does: - 10 FLOPs per 64 bytes loaded = 160 GFLOPS (memory bound on DDR4) - 100 FLOPs per 64 bytes = could hit compute roof --- ## Benchmarking Best Practices ### What to Measure 1. **Wall-clock time** - Actual elapsed time 2. **CPU cycles** - Machine cycles (more stable across machines) 3. **Instructions** - Number of ops executed 4. **Cache misses** - Memory behavior ### Common Pitfalls 1. **Benchmarking debug builds** - Always use `-O3` or equivalent 2. **Single runs** - Need statistical significance 3. **Aliasing effects** - Different CPUs behave differently 4. **Thermal throttling** - Let CPU cool between runs 5. **Background processes** - Close other apps 6. **CPU frequency scaling** - Disable turbo/powersave or use `perf` ### Accurate Timing ```rust // Rust: use std::time or criterion use std::time::Instant; let start = Instant::now(); work(); let elapsed = start.elapsed(); // Multiple runs let runs = 1000; let total: Duration = (0..runs) .map(|_| { let start = Instant::now(); work(); start.elapsed() }) .sum(); let avg = total / runs; ``` --- ## Profiling Workflow ### Step 1: Identify Hotspots ```bash perf record -g ./program perf report ``` Find where most time is spent. ### Step 2: Analyze Why - Is it CPU-bound or memory-bound? - What's the cache miss rate? - Are branches mispredicting? ```bash perf stat -e cycles,instructions,cache-misses,branch-misses ./program ``` ### Step 3: Optimize Apply appropriate optimization based on analysis. ### Step 4: Verify Re-run profiling to confirm improvement. --- ## Platform-Specific Tools ### macOS ```bash # Instruments (GUI) open /Applications/Instruments.app # Sample (CLI) sample ``` ### Windows - **VTune Profiler** (Intel) - Free, excellent - **Visual Studio Profiler** - Built-in - **Windows Performance Toolkit** - WPR/WPA ### All Platforms - **Intel VTune** - Works on AMD too - **AMD μProf** - AMD-specific - **Google Benchmark** - Portable microbenchmarking --- ## Checklist - [ ] Profile before optimizing - [ ] Use multiple runs with statistical analysis - [ ] Identify CPU vs memory bound - [ ] Check cache miss rates - [ ] Check branch misprediction rates - [ ] Verify optimizations with re-profiling - [ ] Benchmark optimized vs unoptimized --- ## Use With Load these skills together for complete performance work: - `performance-optimization` - Apply fixes - `cpu-architecture` - Understand hardware implications