Performance Profiling
Intro
Intuition about performance is unreliable — always profile before
optimizing. Work the cycle: identify the symptom, measure the
baseline, profile the right resource, optimize the top bottleneck,
verify the improvement. One change at a time.
Overview
Performance analysis cycle
Always work the full cycle: Identify -> Measure -> Profile ->
Optimize -> Verify.
- Identify the concern: slow response, high memory, excessive
CPU, I/O stalls
- Measure the baseline with concrete numbers (latency p50/p95/p99,
throughput, RSS)
- Profile with the right tool for the resource type — see
references/profiling-tools.md
- Optimize the top bottleneck only; do not scatter-shot
- Verify with the same measurement from step 2
Never skip measurement. Without a number you cannot tell whether the
change helped or hurt.
CPU profiling
Identify what the application spends CPU time on:
- Use a sampling profiler (not instrumenting) to minimize
overhead
- Collect a representative workload, not a trivial test case
- Generate a flame graph for visual analysis
- Look for wide stacks (hot functions), deep stacks (excess
abstraction), and unexpected functions (regex compilation,
serialization, logging)
Track CPU time per operation, not wall-clock (which includes I/O
waits).
Memory profiling
Identify allocation pressure and leaks:
- Track peak RSS and allocation rate, not just current usage
- For leaks, take heap snapshots at intervals and diff them
- Look for unbounded collections, caches without eviction, event
listener accumulation, and reference cycles in GC languages
- Distinguish a leak (unbounded growth) from high-but-stable usage,
which may be acceptable
I/O profiling
Identify disk, network, or database bottlenecks:
- Compare wall-clock time with CPU time — a large gap is I/O wait
- For databases: enable slow query logging, look for N+1, missing
indexes
- For network: check connection pooling, DNS, TLS handshake overhead
- For disk: check synchronous writes, excessive fsync, unnecessary
file ops
Quick checklist before profiling
- What is the user-visible symptom? (slow page, high bill, OOM)
- What resource is constrained? (CPU, memory, disk, network, DB)
- Constant or intermittent? (steady-state vs spike-triggered)
- What changed recently? Regressions usually correlate with
recent deploys
- What is the acceptable target? (p99 < 200 ms, RSS < 512 MB —
you need a goal to know when you are done)
Gotchas
Agent-specific failure modes — provider-neutral pause-and-self-check items:
- Optimizing before establishing a baseline measurement. Without a concrete before number (p50/p95/p99, RSS, throughput), there is no way to tell whether the change helped, hurt, or made no difference. Establish the baseline first — then optimize — then verify with the same measurement.
- Profiling under trivial or synthetic load. A profiler run against a tight loop with no I/O tells you nothing about production behavior. Collect a workload representative of real traffic — replay production logs, replicate actual access patterns, or drive realistic concurrency before reading the profiler output.
- Chasing secondary bottlenecks before exhausting the primary one. After a profiling pass, fix the top bottleneck first and re-profile. Fixing the second-biggest bottleneck while the primary one still saturates the resource often produces no measurable improvement.
- Reporting wall-clock time when the constrained resource is CPU. A function that takes 200ms wall-clock while waiting for a database query uses almost no CPU. Profiling the wrong resource leads to wrong conclusions. Distinguish CPU time, wall-clock, I/O wait, and memory allocation — they require different tools and different fixes.
- Declaring success after a microbenchmark without re-running under realistic load. Verifying a change with a tight loop under no concurrency and then shipping it is not a verification. Re-run the same realistic workload used for the baseline before declaring the goal met.
- Fixing a performance regression without adding a regression test. A regression fixed once will recur unless a benchmark or load-test encodes the boundary. After every performance fix, add a test that would catch reversion to the slow path.
- Running high-rate sampling profilers against production. Profilers at 100% sampling rate or instrumenting every function call introduce measurable overhead that can itself degrade the system under investigation. Use a low-overhead sampling approach in production; reserve high-rate profiling for staging.
Full reference
Profiling tools by language
references/profiling-tools.md has the full table. Quick picks:
- Python:
py-spy (sampling CPU, attach to running process,
flame graphs); memray (allocations, native + Python frames);
scalene (line-level CPU + memory + GPU); cProfile for built-in
function-level
- Node.js:
clinic.js (Doctor / Bubbleprof / Flame); 0x (flame
graphs); Chrome DevTools for heap snapshots
- Rust:
cargo flamegraph (CPU); criterion (statistical
benchmarks); dhat (heap); perf for hardware counters
- Go:
pprof for CPU/heap/goroutine; trace for scheduler and
GC events; benchstat for statistical comparison
- JVM: JFR (Flight Recorder) — built-in and production-safe;
async-profiler for sampling CPU/alloc/lock with no safepoint
bias; jmap + MAT for heap dumps
Benchmarking and regression detection
- Isolate the code under test — benchmark the function, not the
setup
- Run enough iterations for statistical significance (mean, stddev,
percentiles)
- Control external factors: disable turbo boost, pin CPU frequency,
close other processes
- For regression detection, store baseline results in version
control and compare on each run
# Rust criterion
cargo bench -- --save-baseline main
# After changes:
cargo bench -- --baseline main
Reading flame graphs
- X-axis is alphabetical (not time); width = proportion of
samples
- Y-axis is stack depth, read bottom-up (caller -> callee)
- Wide boxes at the top are hot leaf functions — optimize first
- Wide boxes at the bottom are hot callers — consider algorithmic
changes
- Look for unexpected frames: GC pauses, lock contention, allocator
overhead
- Use differential flame graphs (red/blue) to compare before/after
Common patterns: a single tall tower means one deep call chain
dominates (look for unnecessary abstraction); a wide plateau at the
top means a leaf function consuming most CPU; many thin towers with
the same top function is a memoization candidate; GC/malloc frames
indicate allocation pressure; lock/mutex frames mean contention;
syscall frames (read, write, poll) mean the workload is I/O
bound.
Common optimization patterns
After profiling reveals the bottleneck, apply the right fix:
- Algorithmic — O(n²) -> O(n log n). Always check this first.
- Batching — combine many small operations into fewer large ones
- Caching — reuse computed results, but measure the hit rate
- Pooling — reuse expensive resources (connections, threads,
buffers)
- Lazy evaluation — defer work until actually needed
- Data layout — struct-of-arrays vs array-of-structs for cache
friendliness
General tips
- Always profile a realistic workload, not a microbenchmark
- Profile in an environment close to production — same data
size, same concurrency
- Sampling profilers (
py-spy, async-profiler, perf) are
preferred over instrumenting profilers in production
- Collect profiles for at least 30 seconds for statistical
significance
- Compare before and after with the same workload to validate
improvements
1---2name: performance-profiling3description: |4 Performance analysis and profiling for CPU, memory, and I/O — flame graphs, benchmarks, regression detection. Use when identifying performance bottlenecks, profiling CPU/memory/I/O, interpreting flame graphs, setting up benchmarking or regression detection, or optimizing a slow function or endpoint.5metadata:6 source: https://skillmd.com/skills/projectious-work/performance-profiling7 processkit:8 apiVersion: processkit.projectious.work/v19 id: SKILL-performance-profiling10 version: "1.1.0"11 created: 2026-04-06T00:00:00Z12 category: engineering13---1415# Performance Profiling1617## Intro1819Intuition about performance is unreliable — always profile before20optimizing. Work the cycle: identify the symptom, measure the21baseline, profile the right resource, optimize the top bottleneck,22verify the improvement. One change at a time.2324## Overview2526### Performance analysis cycle2728Always work the full cycle: **Identify -> Measure -> Profile ->29Optimize -> Verify**.30311. **Identify** the concern: slow response, high memory, excessive32 CPU, I/O stalls332. **Measure** the baseline with concrete numbers (latency p50/p95/p99,34 throughput, RSS)353. **Profile** with the right tool for the resource type — see36 `references/profiling-tools.md`374. **Optimize** the top bottleneck only; do not scatter-shot385. **Verify** with the same measurement from step 23940Never skip measurement. Without a number you cannot tell whether the41change helped or hurt.4243### CPU profiling4445Identify what the application spends CPU time on:46471. Use a **sampling** profiler (not instrumenting) to minimize48 overhead492. Collect a representative workload, not a trivial test case503. Generate a flame graph for visual analysis514. Look for **wide stacks** (hot functions), **deep stacks** (excess52 abstraction), and unexpected functions (regex compilation,53 serialization, logging)5455Track **CPU time** per operation, not wall-clock (which includes I/O56waits).5758### Memory profiling5960Identify allocation pressure and leaks:61621. Track **peak RSS** and **allocation rate**, not just current usage632. For leaks, take heap snapshots at intervals and diff them643. Look for unbounded collections, caches without eviction, event65 listener accumulation, and reference cycles in GC languages664. Distinguish a leak (unbounded growth) from high-but-stable usage,67 which may be acceptable6869### I/O profiling7071Identify disk, network, or database bottlenecks:72731. Compare wall-clock time with CPU time — a large gap is I/O wait742. For databases: enable slow query logging, look for N+1, missing75 indexes763. For network: check connection pooling, DNS, TLS handshake overhead774. For disk: check synchronous writes, excessive fsync, unnecessary78 file ops7980### Quick checklist before profiling81821. What is the **user-visible symptom**? (slow page, high bill, OOM)832. What **resource** is constrained? (CPU, memory, disk, network, DB)843. **Constant or intermittent**? (steady-state vs spike-triggered)854. **What changed recently?** Regressions usually correlate with86 recent deploys875. What is the **acceptable target**? (p99 < 200 ms, RSS < 512 MB —88 you need a goal to know when you are done)8990## Gotchas9192Agent-specific failure modes — provider-neutral pause-and-self-check items:9394- **Optimizing before establishing a baseline measurement.** Without a concrete before number (p50/p95/p99, RSS, throughput), there is no way to tell whether the change helped, hurt, or made no difference. Establish the baseline first — then optimize — then verify with the same measurement.95- **Profiling under trivial or synthetic load.** A profiler run against a tight loop with no I/O tells you nothing about production behavior. Collect a workload representative of real traffic — replay production logs, replicate actual access patterns, or drive realistic concurrency before reading the profiler output.96- **Chasing secondary bottlenecks before exhausting the primary one.** After a profiling pass, fix the top bottleneck first and re-profile. Fixing the second-biggest bottleneck while the primary one still saturates the resource often produces no measurable improvement.97- **Reporting wall-clock time when the constrained resource is CPU.** A function that takes 200ms wall-clock while waiting for a database query uses almost no CPU. Profiling the wrong resource leads to wrong conclusions. Distinguish CPU time, wall-clock, I/O wait, and memory allocation — they require different tools and different fixes.98- **Declaring success after a microbenchmark without re-running under realistic load.** Verifying a change with a tight loop under no concurrency and then shipping it is not a verification. Re-run the same realistic workload used for the baseline before declaring the goal met.99- **Fixing a performance regression without adding a regression test.** A regression fixed once will recur unless a benchmark or load-test encodes the boundary. After every performance fix, add a test that would catch reversion to the slow path.100- **Running high-rate sampling profilers against production.** Profilers at 100% sampling rate or instrumenting every function call introduce measurable overhead that can itself degrade the system under investigation. Use a low-overhead sampling approach in production; reserve high-rate profiling for staging.101102## Full reference103104### Profiling tools by language105106`references/profiling-tools.md` has the full table. Quick picks:107108- **Python**: `py-spy` (sampling CPU, attach to running process,109 flame graphs); `memray` (allocations, native + Python frames);110 `scalene` (line-level CPU + memory + GPU); `cProfile` for built-in111 function-level112- **Node.js**: `clinic.js` (Doctor / Bubbleprof / Flame); `0x` (flame113 graphs); Chrome DevTools for heap snapshots114- **Rust**: `cargo flamegraph` (CPU); `criterion` (statistical115 benchmarks); `dhat` (heap); `perf` for hardware counters116- **Go**: `pprof` for CPU/heap/goroutine; `trace` for scheduler and117 GC events; `benchstat` for statistical comparison118- **JVM**: JFR (Flight Recorder) — built-in and production-safe;119 `async-profiler` for sampling CPU/alloc/lock with no safepoint120 bias; `jmap` + MAT for heap dumps121122### Benchmarking and regression detection1231241. Isolate the code under test — benchmark the function, not the125 setup1262. Run enough iterations for statistical significance (mean, stddev,127 percentiles)1283. Control external factors: disable turbo boost, pin CPU frequency,129 close other processes1304. For regression detection, store baseline results in version131 control and compare on each run132133```bash134# Rust criterion135cargo bench -- --save-baseline main136# After changes:137cargo bench -- --baseline main138```139140### Reading flame graphs141142- **X-axis** is alphabetical (not time); width = proportion of143 samples144- **Y-axis** is stack depth, read bottom-up (caller -> callee)145- **Wide boxes at the top** are hot leaf functions — optimize first146- **Wide boxes at the bottom** are hot callers — consider algorithmic147 changes148- Look for unexpected frames: GC pauses, lock contention, allocator149 overhead150- Use **differential** flame graphs (red/blue) to compare before/after151152Common patterns: a single tall tower means one deep call chain153dominates (look for unnecessary abstraction); a wide plateau at the154top means a leaf function consuming most CPU; many thin towers with155the same top function is a memoization candidate; GC/malloc frames156indicate allocation pressure; lock/mutex frames mean contention;157syscall frames (`read`, `write`, `poll`) mean the workload is I/O158bound.159160### Common optimization patterns161162After profiling reveals the bottleneck, apply the right fix:163164- **Algorithmic** — O(n²) -> O(n log n). Always check this first.165- **Batching** — combine many small operations into fewer large ones166- **Caching** — reuse computed results, but measure the hit rate167- **Pooling** — reuse expensive resources (connections, threads,168 buffers)169- **Lazy evaluation** — defer work until actually needed170- **Data layout** — struct-of-arrays vs array-of-structs for cache171 friendliness172173### General tips174175- Always profile a **realistic workload**, not a microbenchmark176- Profile in an environment **close to production** — same data177 size, same concurrency178- Sampling profilers (`py-spy`, `async-profiler`, `perf`) are179 preferred over instrumenting profilers in production180- Collect profiles for **at least 30 seconds** for statistical181 significance182- Compare **before and after** with the same workload to validate183 improvements