Home Knowledge Base CPU Cache Optimization

CPU Cache Optimization — writing code that exploits the CPU's memory hierarchy (L1→L2→L3→DRAM) to minimize expensive cache misses, potentially achieving 10-100x performance improvement.

Memory Hierarchy Latency

LevelSizeLatencyBandwidth
L1 Cache32-64 KB~1 ns (4 cycles)~1 TB/s
L2 Cache256 KB-1 MB~3 ns (12 cycles)~500 GB/s
L3 Cache8-64 MB~10 ns (40 cycles)~200 GB/s
DRAM16-256 GB~70 ns (280 cycles)~50 GB/s

Key Optimization Strategies

1. Spatial Locality: Access data sequentially (cache lines are 64 bytes)

2. Temporal Locality: Reuse data while it's still in cache

3. Avoid False Sharing: Different threads writing to same cache line → invalidation ping-pong

4. Prefetching: CPU hardware prefetcher detects sequential/strided patterns. Use __builtin_prefetch() for irregular patterns

Cache optimization is the #1 performance technique for CPU-bound code — an algorithm that's cache-friendly can outperform an otherwise "faster" algorithm with poor locality.

cpu cache optimizationcache friendly codecache missmemory hierarchy

Explore 500+ Semiconductor & AI Topics

From EUV lithography to CUDA optimization — search the full knowledge base or chat with our AI assistant.