Notes
All notes

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} \]

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.

QQuestionA compiler reduces instruction count by 20% but raises CPI from 1.2 to

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:

QQuestionWhy did clock frequencies stop rising around 2005?
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:

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 \]

QQuestionA program has IPC 0.5. What does that mean in cycles per instruction?
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:

The law applies to optimization in general: speeding up the 10% that is not the bottleneck buys almost nothing.

QQuestionA profiler says 60% of the time is in a function you can make 10×

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

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:

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).

QQuestionWhy can adding more threads improve throughput but not latency?
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:

// 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;
QQuestionWhy does splitting a sum into four accumulators help?
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.

QQuestionWhy is a sort of random data often slower than a sort of sorted data,

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:

QQuestionWhy does blocking (tiling) a matrix multiply help?
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.

QQuestionDoes swapping the loops always fix a column-major access?
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

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.

QQuestionWhen is AoS the better choice?
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:

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.

QQuestionWhy might -O3 -march=native produce a binary that crashes on another

machine?

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

QQuestionA loop gets slower after adding -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.