Performance and Optimization (COA Core #7)
Performance questions reduce to one equation and a few multipliers: instructions, cycles per instruction, and clock time. Everything else — caches, branches, vectorization, memory layout — changes one of those terms. Knowing which term a change affects is most of the skill.
CPU execution time
\[ T_{\text{CPU}} = \text{IC} \times \text{CPI} \times T_{\text{cycle}} = \frac{\text{IC} \times \text{CPI}}{f} \]
- IC: instruction count, decided by the compiler and ISA.
- CPI: average cycles per instruction.
- \(T_{\text{cycle}}\): clock period, the inverse of frequency \(f\).
- IPC = \(1/\text{CPI}\).
Worked: \(10^9\) instructions, CPI 1.5, 3 GHz:
\[ T = 10^9 \times 1.5 \times \frac{1}{3 \times 10^9} = 0.5 \text{ s} \]
Doubling the clock halves the time only if CPI stays the same. It usually does not: faster clocks need deeper pipelines, which raise misprediction penalties.
1.5. Is the program faster?
ASolution
New time is proportional to \(0.8 \times 1.5 = 1.2\) versus \(1 \times 1.2 = 1.2\), so it is a wash. Fewer instructions that each take longer can cancel out.
Clock cycles and frequency
\(T_{\text{cycle}}\) is set by the critical path: the longest combinational delay between two registers. Raising frequency means shortening that path, usually by splitting work into more pipeline stages.
Limits:
- Power: \(P \approx C V^2 f\). Frequency and voltage together hit a wall around 4–5 GHz for desktop CPUs.
- Pipeline depth: more stages mean more hazards and a larger misprediction penalty.
- Memory: a faster core waits longer, relatively, for DRAM. The “memory wall” is the growing gap between CPU cycles and memory latency.
ASolution
Power density. Doubling frequency at the same voltage doubles dynamic power, and leakage rises with smaller transistors, so the chip cannot be cooled. The industry moved to more cores and wider SIMD instead.
CPI and IPC
\[ \text{CPI} = \frac{\text{total cycles}}{\text{instruction count}} = \text{base CPI} + \text{stall cycles per instruction} \]
A pipelined core with no stalls has CPI 1 (IPC 1). Superscalar cores can issue several instructions per cycle, so CPI below 1 and IPC above 1 are normal.
Sources of stalls:
- cache misses (data and instruction),
- branch mispredictions,
- load-use and other data hazards,
- resource conflicts,
- TLB misses.
Example: base CPI 1, 5% L1 misses with 20-cycle penalty, 2% branch mispredicts with 15-cycle penalty:
\[ \text{CPI} = 1 + 0.05(20) + 0.02(15) = 1 + 1.0 + 0.3 = 2.3 \]
ASolution
CPI = 2. On average, each instruction takes two cycles, which is typical for a workload dominated by cache misses or dependencies on a narrow core.
Amdahl’s law
If a fraction \(p\) of the work can be sped up by a factor \(s\), the total speedup is
\[ \text{speedup}(s) = \frac{1}{(1-p) + p/s} \]
With unlimited \(s\), the ceiling is \(1/(1-p)\).
Examples:
- \(p = 0.9\), \(s = 8\): \(1/(0.1 + 0.9/8) = 1/0.2125 = 4.71\).
- \(p = 0.95\), \(s = 16\): \(1/(0.05 + 0.059375) = 9.14\).
- \(p = 0.5\): never above 2×, no matter how many cores.
The law applies to optimization in general: speeding up the 10% that is not the bottleneck buys almost nothing.
faster. What is the overall speedup?
ASolution
\(1/(0.4 + 0.6/10) = 1/0.46 = 2.17\times\). The remaining 40% caps the gain.
Latency versus throughput
- Latency: time for one operation end to end.
- Throughput: operations completed per unit time.
A pipeline has latency \(k\) cycles but throughput one per cycle. Memory has latency of 100 ns but enormous aggregate throughput because many requests are in flight. Optimizations differ:
- To improve latency, shorten the critical path (fewer dependent operations).
- To improve throughput, increase parallelism and overlap (more outstanding requests, wider SIMD, more cores).
A common mistake is measuring throughput while the code is latency-bound (a pointer chase) or measuring latency while it is throughput-bound (a streaming loop).
ASolution
Threads overlap independent work, so more completes per second. Each individual operation still takes the same time.
Instruction-level parallelism
ILP is parallelism inside one thread: independent instructions that can execute together. Superscalar issue, out-of-order execution, and register renaming exploit it.
Limits:
- True dependencies (RAW): a consumer cannot start before its producer.
- Window size: the reorder buffer and scheduler hold a finite number of instructions.
- Branches: speculation limits how far ahead the core can look.
- Memory dependencies: the compiler and CPU must be conservative about aliasing.
// dependent chain: latency-bound
for (int i = 1; i < n; ++i) a[i] = a[i-1] + b[i];
// independent iterations: can overlap
for (int i = 0; i < n; ++i) c[i] = a[i] + b[i];
Unrolling and multiple accumulators break dependency chains:
int s0 = 0, s1 = 0;
for (int i = 0; i + 1 < n; i += 2) { s0 += a[i]; s1 += a[i+1]; }
int s = s0 + s1;
ASolution
Floating-point and integer adds have latency greater than one cycle. Four independent chains let the pipeline keep four adds in flight instead of waiting for each previous result.
Branch prediction accuracy
Mispredictions cost cycles and waste fetched work:
\[ \text{CPI}_{\text{branch}} = b \cdot m \cdot p \]
where \(b\) is the branch fraction, \(m\) the misprediction rate, and \(p\) the penalty.
Example: 20% branches, 5% misprediction, 15-cycle penalty →
\[ 0.20 \times 0.05 \times 15 = 0.15 \text{ CPI} \]
That is a 15% slowdown from branches alone. Unpredictable data-dependent branches (partitioning, binary search, compression) are the worst case; branchless code often wins:
// branchy: mispredicts on random data
if (a[i] > 0) sum += a[i];
// branchless: always the same instructions
sum += (a[i] > 0) ? a[i] : 0;
A predictable branch (loop counter, error check) costs almost nothing. The predictor learns the pattern.
even with the same instruction count?
ASolution
Branch mispredictions. Quicksort’s partition branch is unpredictable on random input; on nearly sorted input the pattern is easier to predict.
Cache misses and performance
The memory wall: DRAM latency in cycles keeps growing as clocks and cores improve. A single L3 miss can cost 200+ cycles.
\[ \text{AMAT} = t_{\text{hit}} + \text{miss rate} \times \text{miss penalty} \]
If a loop makes one load per iteration and 10% miss L1 with a 50-cycle L2 penalty, the average load costs \(1 + 0.1 \times 50 = 6\) cycles. The arithmetic is not the bottleneck; the memory is.
Techniques:
- improve locality (blocking, loop ordering),
- reduce the working set,
- prefetch (
__builtin_prefetch, hardware prefetchers), - use contiguous data structures,
- align hot data to cache lines.
ASolution
It reuses a tile of both matrices while it is still in cache, reducing the number of times each element is fetched from memory.
Row-major versus column-major
C and C++ store 2D arrays row-major: a[i][j] is at base + (i*cols + j)*sizeof(T).
Fortran, MATLAB, and some libraries use column-major.
For a 1024×1024 int matrix, one row is 4 KB — 64 cache lines. Traversing by rows
uses every byte of each line; traversing by columns jumps 4 KB per step, so almost
every access is a new line.
// good: contiguous
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
sum += a[i][j];
// bad: stride = one row
for (int j = 0; j < n; ++j)
for (int i = 0; i < n; ++i)
sum += a[i][j];
The second loop can be an order of magnitude slower on large matrices. Hardware prefetchers help with streams, not with 4 KB strides.
ASolution
Only if the inner loop becomes contiguous in memory. Swapping loops changes which index varies fastest; it must match the storage order.
Data locality and layout
- Arrays beat linked lists for scans: contiguous, prefetchable, one line per 16 ints.
- Struct layout matters: hot fields together, cold fields elsewhere.
- Pointer chasing is latency-bound: each load depends on the previous one, so ILP cannot hide it.
- Prefetching works for predictable strides; it cannot help random access.
struct Particle { float x, y, z, vx, vy, vz; }; // 24 bytes, AoS
If a loop only needs positions, it still loads velocities because they share the line. Splitting the arrays fixes that.
Array of Structures versus Structure of Arrays
| AoS | SoA | |
|---|---|---|
| Layout | {x,y,z} per element |
all x, then all y, then all z |
| Cache use | wastes bytes on unused fields | uses exactly what is read |
| SIMD | needs gathers or shuffles | contiguous, vectorizes directly |
| Code | natural for objects | natural for kernels |
// AoS
struct Particle { float x, y, z; };
std::vector<Particle> ps;
// SoA
struct Particles { std::vector<float> x, y, z; };
For a physics step that updates positions from velocities, SoA keeps the three streams contiguous and lets the compiler emit SIMD loads. AoS is fine when all fields are used together or the object is accessed as a unit.
ASolution
When the code touches most fields of one object at a time, or when objects are small and accessed individually (graph nodes, scene objects). SoA wins for field-wise bulk processing.
SIMD and vectorization
SIMD executes one instruction on several values. x86 widths:
| Extension | Register width | Floats per op |
|---|---|---|
| SSE | 128 bits | 4 |
| AVX2 | 256 bits | 8 |
| AVX-512 | 512 bits | 16 |
Compilers auto-vectorize simple loops when they can prove:
- no loop-carried dependencies (or they are associative and reorderable),
- no aliasing that would change results,
- contiguous or strided access the ISA supports,
- no function calls that block vectorization.
void add(const float* a, const float* b, float* c, int n) {
for (int i = 0; i < n; ++i) c[i] = a[i] + b[i]; // vectorizes
}
restrict (or __restrict) tells the compiler the pointers do not overlap. -O3
-march=native enables the widest ISA available; -fno-tree-vectorize disables it
for comparison.
Vectorization is why SoA matters: AoS needs a gather (slow) or a transpose; SoA loads 8 contiguous floats in one instruction.
-O3 -march=native produce a binary that crashes on anothermachine?
ASolution
-march=native enables instructions the target machine has (AVX-512, for
example). An older CPU without them raises an illegal instruction fault. Build for
a baseline or dispatch at runtime.
Bugs and edge cases
- Optimizing the wrong thing. Measure first; the bottleneck is often not where the code looks slow.
- Comparing times without fixing the workload. Cache warmth, input size, and compiler flags change everything.
- Ignoring the memory wall. A 10% instruction reduction can lose to a 10% increase in cache misses.
- Assuming vectorization happened. Check the assembly or use
-fopt-info-vec. - Microbenchmarking dead code. The compiler may delete a loop whose result is
unused; use
volatileor consume the result. - Frequency scaling and turbo. Wall-clock timings vary with power and thermal state; pin the CPU and repeat.
- Over-padding for false sharing. It can hurt a later streaming pass.
-O3. What are plausible causes?ASolution
Aggressive vectorization with a gather, code bloat hurting the instruction cache,
or autovectorization changing floating-point association. Inspect the generated
assembly and try -O2 for comparison.
Next: Parallel and GPU Architecture (COA Core #8) — SIMT, warps, coalescing, and CUDA basics.