name: cpu-architecture description: CPU internals reference — pipelines, branch prediction, cache hierarchy, SIMD, instruction-level parallelism. Use when understanding hardware performance bottlenecks, writing cache-friendly code, or reasoning about hot path behavior. license: MIT
What I Do
Explain CPU architecture concepts that affect performance. Use when optimizing hot paths or understanding why code runs faster or slower on different hardware.
CPU Pipeline Basics
How CPUs Execute Instructions
Modern CPUs use pipelining - overlapping execution of multiple instructions:
Stage 1: Fetch → Stage 2: Decode → Stage 3: Execute → Stage 4: Writeback
Without pipeline: 4 cycles per instruction With pipeline: ~1 cycle per instruction (after fill)
Pipeline Hazards
Three types of hazards that stall the pipeline:
- Structural hazards - Hardware can't support all combinations
- Data hazards - Instruction needs result from previous instruction
- Control hazards - Branch changes flow of execution
Instruction-Level Parallelism (ILP)
Multiple instructions execute simultaneously when independent:
// These can all execute in parallel (different registers)
a = b + c;
d = e + f;
g = h + i;
ILP is limited by:
- Data dependencies (can't reorder dependent ops)
- Register pressure (need enough registers)
- Branch prediction (mispredictions flush pipeline)
Branch Prediction
Why Branches Are Expensive
Branches cause pipeline stalls when prediction is wrong:
Good prediction: 1 cycle penalty
Misprediction: 10-20 cycle penalty (pipeline flush)
Branch Predictors
Static predictors:
- Always predict not-taken (or taken)
- Used when no history
Dynamic predictors:
- Two-level adaptive: Uses branch history + pattern table
- TAGE: Tagged geometric history length (modern, best)
Patterns That Predict Well
// Predictable: always true in this codebase
if (ptr != NULL) // NULL check - usually not NULL
ptr->process();
// Unpredictable: depends on data
if (value > threshold) // Data-dependent
process();
Branch Target Buffer (BTB)
Caches branch targets:
- Miss in BTB = 2+ cycle penalty
- Critical for indirect branches (virtual calls, switches)
Cache Hierarchy
Cache Levels
L1: ~32 KB (4-5 cycles) - Code + Data (often split)
L2: ~256 KB (12-15 cycles) - Unified
L3: ~8 MB (40-50 cycles) - Shared across cores
RAM: ~GB (200+ cycles) - Main memory
Cache Lines
- 64 bytes is standard (most x86/ARM)
- Loading 1 byte loads entire cache line
- Sequential access = 1 line load per N bytes
Cache Associativity
Direct-mapped: 1 way - Fast but many conflicts
N-way set-associative: N choices - Slower but fewer conflicts
Fully associative: All locations - Expensive hardware
Typical:
- L1: 8-way
- L2: 8-way
- L3: 16-way
Eviction Policies
- LRU (Least Recently Used) - Most common
- PLRU (Pseudo-LRU) - Approximate LRU, cheaper
- Random - Used in some L3 caches
Memory Access Patterns
Spatial Locality
Good: Access nearby memory
// Sequential - 1 cache line per 64 bytes
for (int i = 0; i < n; i++)
sum += array[i];
Bad: Strided access
// Every 64th element = loads 1 line per access
for (int i = 0; i < n; i += 64)
sum += array[i];
Temporal Locality
Good: Reuse data soon
// Same data used multiple times
for (int i = 0; i < n; i++)
sum += matrix[row][i]; // row stays in cache
Bad: Touch each line once
// No reuse - loads and discards
for (int i = 0; i < n; i++)
process(large_array[i]); // never revisited
Prefetching
Hardware prefetcher:
- Detects sequential patterns
- Loads cache lines before needed
Software prefetcher:
// Manual prefetch (rarely needed)
__builtin_prefetch(&array[i + 16], 0, 3);
// hint: 0 = read, 3 = high locality
Instruction Latency and Throughput
Latency vs Throughput
- Latency: Cycles to complete one operation
- Throughput: Operations per cycle (inverse of latency for independent ops)
| Operation | Latency | Throughput |
|---|---|---|
| Integer add | 1 | 1 |
| Integer multiply | 3-5 | 1 |
| Floating-point add | 4 | 2 |
| Floating-point multiply | 4-5 | 1-2 |
| Load from L1 | 4 | 2-3 |
| Load from L2 | 12 | ~1 |
| Load from RAM | 200+ | < 0.1 |
Port Pressure
CPUs have limited execution ports. Too many operations of same type = stall:
典型 x86端口分配:
Port 0: ALU, FP add
Port 1: ALU, FP mul
Port 2: Load
Port 3: Store
Port 5: ALU, branch
Memory Ordering
Weak vs Strong Ordering
Strong ordering (x86):
- Loads can't reorder with loads
- Stores can't reorder with stores
- Store-load can reorder
Weak ordering (ARM, POWER):
- Can reorder almost anything
- Memory barriers needed for correctness
Memory Barriers
// C11 / C++11
atomic_thread_fence(memory_order_seq_cst); // Full barrier
atomic_thread_fence(memory_order_release); // Stores before this visible
atomic_thread_fence(memory_order_acquire); // Loads after this see prior stores
Why It Matters
On weak memory order CPUs:
- Compiler can reorder
- CPU can reorder
- Without barriers, data races cause unexpected behavior
Out-of-Order Execution
How OoO Works
CPU reorders instructions to hide latency:
- Rename registers - Avoid false dependencies
- Issue - Ready instructions go to execution units
- Complete - Results written in program order
Limitations
- ROB size - Reorder buffer limits in-flight instructions
- Register file - Physical registers limited
- Dependencies - True dependencies can't be hidden
What Breaks OoO
- Many memory loads with unknown addresses
- Too many instructions dependent on each other
- Large code working set
SIMD and Vectorization
Vector Registers
SSE: 128-bit = 4 × f32 or 2 × f64
AVX2: 256-bit = 8 × f32 or 4 × f64
AVX-512: 512-bit = 16 × f32 or 8 × f64
Auto-Vectorization
Compilers auto-vectorize when:
- Contiguous memory access
- No branches (or predictable)
- No aliasing
- Enough iterations
Manual Vectorization
Use intrinsics or portable SIMD:
use std::simd::prelude::*;
let a = Simd::<f32, 8>::from_slice(&data[i..]);
let b = a * Simd::splat(2.0);
b.copy_to_slice(&mut result[i..]);
Common Performance Killers
1. Cache Thrashing
// Bad: Multiple arrays accessed in same pattern
for (int i = 0; i < n; i++)
a[i] = b[i] + c[i]; // All three compete for cache
Fix: Process in blocks or reorder
2. False Sharing
// Bad: Different threads modify adjacent data
struct { volatile long counter; } slots[16];
#pragma omp parallel for
for (int i = 0; i < 16; i++)
slots[i].counter++; // Cache line bounces between cores
Fix: Pad to cache line size
3. Branch in Hot Path
// Bad: Branch every iteration
for (int i = 0; i < n; i++)
if (arr[i] > 0)
pos++;
else
neg++;
Fix: Branchless alternative or hint compiler
4. Indirect Branch
// Virtual call or function pointer
auto fn = handlers[tag];
fn(data); // Hard to predict
Fix: Devirtualize, or use jump table (likely for switch)
CPU-Specific Optimization
Target Architecture
# Compile for specific CPU
gcc -march=native -O3 program.c # Build machine
gcc -march=skylake -O3 program.c # Specific target
# Cross-compile
gcc -march=armv8-a -O3 program.c # ARM64
CPU Features to Use
| Feature | Benefit |
|---|---|
| AVX2/AVX-512 | Wider SIMD |
| BMI1/BMI2 | Fast bit operations |
| FMA | Fused multiply-add |
| CET | Security (if needed) |
| SIMD | Parallelism |
Feature Detection
// Rust: runtime feature detection
if is_x86_feature_detected!("avx2") {
// Use AVX2 code path
}
Checklist
- Understand memory hierarchy (L1/L2/L3/RAM)
- Minimize cache misses (spatial + temporal locality)
- Predict branches correctly or make branchless
- Use SIMD for data-parallel operations
- Avoid false sharing in multithreaded code
- Consider memory ordering on weak CPUs
Related Skills
performance-optimization- Apply optimizationsprofiling-analysis- Measure impactbranchless-programming- Eliminate branchesperformance-simd- SIMD optimization