# Valgrind cachegrind **cachegrind** simulates CPU caches (L1 instruction, L1 data, L2, L3) and reports cache miss rates and memory behavior. Like callgrind, it counts deterministically without sampling. Use it to understand cache efficiency and validate optimization strategies. ```bash valgrind --tool=cachegrind ./program cg_annotate cachegrind.out.12345 ``` cachegrind simulates a CPU cache hierarchy and tracks every load and store, counting hits and misses. The output shows per-function cache statistics—useful for understanding which functions have poor cache behavior. **Output:** ``` I refs: 1,000,000 I1 misses: 5,000 (0.5%) LLi misses: 1,000 D refs: 2,000,000 D1 misses: 50,000 (2.5%) LLd misses: 10,000 LL refs: 3,000,000 LL misses: 20,000 (0.67%) ``` "I" = instruction cache, "D" = data cache, "LL" = last-level (L3). The report shows misses as a count and percentage of all accesses. **Per-function annotation:** ```bash cg_annotate --auto=yes cachegrind.out.12345 ``` This shows source code (or disassembly) with cache miss counts annotated on each line—revealing exactly which instructions cause cache misses. **Comparing cache profiles:** Validate that your optimization actually improved cache behavior: ```bash valgrind --tool=cachegrind --outfile=cache1.out ./prog_v1 valgrind --tool=cachegrind --outfile=cache2.out ./prog_v2 cg_annotate cache1.out cache2.out ``` This shows side-by-side cache statistics for two versions of the program. **Configuration:** By default, cachegrind simulates a typical modern x86 cache (L1i 32KB, L1d 32KB, L2 256KB, L3 8MB). For embedded systems or older CPUs, configure the cache sizes: ```bash valgrind --tool=cachegrind --I1=32,64,64 --D1=32,64,64 --LL=256,4,64 ./program ``` This sets I1 (instruction cache) to 32KB, 64-byte lines, 64-way associative, and so on. **Advantages:** 1. Deterministic: reproducible cache profiles 2. Insightful: per-line cache miss analysis 3. Configurable: simulate different cache architectures **Disadvantages:** 1. Simulation: doesn't reflect real CPU prefetching or TLB behavior 2. Slow: 5-20x overhead 3. Not real-world: simulated miss counts may differ from hardware due to prefetching and out-of-order execution Use cachegrind to understand algorithmic cache behavior and validate optimization strategies. Use [[perf]] with cache-related events to measure real hardware cache misses.