The rule: bytes you fetch but do not use are wasted bandwidth
The Systems and Low-Latency Basics lesson gives the latency ladder (L1 about 1 ns, main memory about 100 ns) and the rules of thumb. This lesson tests those rules with a benchmark you can run, and teaches you to explain each number, because interviewers increasingly ask "why is this faster?" rather than "which is faster?".
Three facts drive everything:
- Memory moves in cache lines (64 bytes on most x86 parts; this lesson's Apple M1 reports 128 via
sysctl hw.cachelinesize). Reading one byte costs the whole line. - The hardware prefetcher detects sequential and strided access and fetches lines before you ask. Contiguous arrays get this for free.
- The out-of-order core can have many independent misses in flight at once, but a dependent chain (the next address is inside the current node) serialises them, paying full memory latency each step.
The benchmark
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdio>
#include <list>
#include <numeric>
#include <random>
#include <thread>
#include <vector>
using clk = std::chrono::steady_clock;
template <class F>
double best_ms(F&& f, int reps = 5) {
double best = 1e300;
for (int r = 0; r < reps; ++r) {
auto t0 = clk::now();
f();
best = std::min(best, std::chrono::duration<double, std::milli>(clk::now() - t0).count());
}
return best;
}
struct TradeAoS { // 64 bytes: one trade per cache line
double price, qty, fee, ts;
long id, venue, flags, pad;
};
static_assert(sizeof(TradeAoS) == 64);
struct TradesSoA {
std::vector<double> price, qty, fee, ts;
std::vector<long> id, venue, flags;
};
int main() {
constexpr std::size_t N = 10'000'000;
volatile double sink = 0;
// 1. AoS vs SoA: sum one field.
std::vector<TradeAoS> aos(N);
TradesSoA soa;
soa.qty.resize(N);
for (std::size_t i = 0; i < N; ++i) aos[i].qty = soa.qty[i] = double(i % 100);
double t_aos = best_ms([&] { double s = 0; for (auto& t : aos) s += t.qty; sink = s; });
double t_soa = best_ms([&] { double s = 0; for (double q : soa.qty) s += q; sink = s; });
std::printf("sum qty, AoS (64-byte records): %6.2f ms\n", t_aos);
double t_soa4 = best_ms([&] {
double s0 = 0, s1 = 0, s2 = 0, s3 = 0;
for (std::size_t i = 0; i < N; i += 4) {
s0 += soa.qty[i]; s1 += soa.qty[i + 1]; s2 += soa.qty[i + 2]; s3 += soa.qty[i + 3];
}
sink = s0 + s1 + s2 + s3;
});
std::printf("sum qty, SoA (8-byte column): %6.2f ms\n", t_soa);
std::printf("sum qty, SoA, 4 accumulators: %6.2f ms\n", t_soa4);
// 2. vector vs list, and a list whose nodes are scattered.
constexpr std::size_t M = 2'000'000;
std::vector<long> vec(M);
std::iota(vec.begin(), vec.end(), 0);
std::list<long> fresh(vec.begin(), vec.end()); // nodes allocated in order: often adjacent
std::list<long> shuffled;
{
std::vector<std::list<long>::iterator> its;
std::list<long> tmp(vec.begin(), vec.end());
for (auto it = tmp.begin(); it != tmp.end(); ++it) its.push_back(it);
std::shuffle(its.begin(), its.end(), std::mt19937_64{42});
for (auto it : its) shuffled.splice(shuffled.end(), tmp, it); // relink, nodes stay put
}
auto sum = [&](auto& c) { long s = 0; for (long x : c) s += x; sink = double(s); };
double t_vec = best_ms([&] { sum(vec); });
double t_fresh = best_ms([&] { sum(fresh); });
double t_shuf = best_ms([&] { sum(shuffled); });
std::printf("sum 2M longs, vector: %6.2f ms (%5.2f ns/elem)\n", t_vec, t_vec * 1e6 / M);
std::printf("sum 2M longs, list (in order): %6.2f ms (%5.2f ns/elem)\n", t_fresh, t_fresh * 1e6 / M);
std::printf("sum 2M longs, list (shuffled): %6.2f ms (%5.2f ns/elem)\n", t_shuf, t_shuf * 1e6 / M);
// 3. False sharing: two threads each increment their own counter.
struct Packed { std::atomic<long> a{0}, b{0}; };
struct Padded { alignas(128) std::atomic<long> a{0}; alignas(128) std::atomic<long> b{0}; };
constexpr long K = 50'000'000;
auto race = [&](auto& c) {
std::thread t1([&] { for (long i = 0; i < K; ++i) c.a.fetch_add(1, std::memory_order_relaxed); });
std::thread t2([&] { for (long i = 0; i < K; ++i) c.b.fetch_add(1, std::memory_order_relaxed); });
t1.join(); t2.join();
};
Packed packed; Padded padded;
double t_packed = best_ms([&] { race(packed); }, 3);
double t_padded = best_ms([&] { race(padded); }, 3);
std::printf("2 threads x 50M increments, same line: %7.1f ms\n", t_packed);
std::printf("2 threads x 50M increments, padded (128B): %7.1f ms\n", t_padded);
}
Built with c++ -std=c++20 -O2 -Wall and run on an Apple M1 (best of 5 repetitions per line, best of 3 for the threaded test):
sum qty, AoS (64-byte records): 15.44 ms
sum qty, SoA (8-byte column): 11.25 ms
sum qty, SoA, 4 accumulators: 3.42 ms
sum 2M longs, vector: 0.43 ms ( 0.21 ns/elem)
sum 2M longs, list (in order): 2.47 ms ( 1.23 ns/elem)
sum 2M longs, list (shuffled): 236.81 ms (118.41 ns/elem)
2 threads x 50M increments, same line: 509.4 ms
2 threads x 50M increments, padded (128B): 129.1 ms
These timings are from one machine and will differ on yours, and they vary between runs: over five runs AoS ranged from 15 to 31 ms, the shuffled list from 118 to 161 ns per element, and the false-sharing pair from 427 to 509 ms versus 129 to 169 ms. Ratios are more stable than absolute values; report them, and always state the hardware.
Explaining each result
AoS versus SoA. The AoS loop touches one 8-byte field per 64-byte record, so it streams MB to use 80 MB: it is bandwidth-bound. The SoA column is only 80 MB. Yet the plain SoA loop is barely faster. Why? It is latency-bound on the floating-point add: s += q is a chain of dependent additions, and at roughly 3 cycles per add at about 3.2 GHz that is about ns ms, close to the measured 10–12 ms. The compiler may not reorder floating-point additions (it would change the rounding) without -ffast-math. Four independent accumulators break the chain, and the SoA loop drops to about 3 ms: now the layout advantage shows. Lesson: a layout change only pays once memory is the bottleneck; check which resource you are limited by.
Vector versus list. The integer vector sum vectorises and streams: 0.2 ns per element. A list built in order is 6 to 8 times slower even though its nodes happen to be nearly adjacent in memory (the allocator handed them out sequentially), because each step is a dependent load of the next pointer and each node (two pointers plus the value) is at least three times larger than the value. After shuffling the links (same nodes, same addresses, random order), every step is a cache and TLB miss that cannot overlap with the next: about 120 to 160 ns, the memory latency figure, and several hundred times slower than the vector. Real long-lived lists look like the shuffled one after a day of inserts and deletes.
False sharing. In Packed, a and b share a cache line. Each fetch_add needs the line in exclusive state, so the line ping-pongs between the two cores. Aligning each counter to its own line makes the threads independent, about 3 to 4 times faster here (2.7x to 3.9x across runs). The padding is 128 bytes because that is this CPU's line size; std::hardware_destructive_interference_size is the portable constant, but libc++ reports 64 on this M1, so check the hardware rather than trusting the constant blindly.
Prefetching: measure before you trust it
__builtin_prefetch(addr) (GCC and Clang) asks the CPU to start loading a line you will need soon. It is tempting for a random gather:
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <numeric>
#include <random>
#include <vector>
using clk = std::chrono::steady_clock;
template <class F>
double best_ms(F&& f) {
double b = 1e300;
for (int r = 0; r < 5; ++r) {
auto t0 = clk::now();
f();
b = std::min(b, std::chrono::duration<double, std::milli>(clk::now() - t0).count());
}
return b;
}
int main() {
constexpr std::size_t N = 1 << 24; // 16M doubles = 128 MB, far larger than cache
std::vector<double> table(N, 1.0);
std::vector<unsigned> idx(N);
std::iota(idx.begin(), idx.end(), 0u);
std::shuffle(idx.begin(), idx.end(), std::mt19937{7}); // random gather, indices known ahead
volatile double sink = 0;
double plain = best_ms([&] {
double s = 0;
for (std::size_t i = 0; i < N; ++i) s += table[idx[i]];
sink = s;
});
double pref = best_ms([&] {
double s = 0;
constexpr std::size_t D = 16; // prefetch distance, tuned by measurement
for (std::size_t i = 0; i < N; ++i) {
if (i + D < N) __builtin_prefetch(&table[idx[i + D]]);
s += table[idx[i]];
}
sink = s;
});
std::printf("random gather: plain %.1f ms, with __builtin_prefetch %.1f ms\n", plain, pref);
}
Two runs on the M1:
random gather: plain 114.7 ms, with __builtin_prefetch 165.1 ms
random gather: plain 93.1 ms, with __builtin_prefetch 116.8 ms
The prefetch made it slower. The loads table[idx[i]] are independent of each other, so the out-of-order core already issues many of them ahead; the prefetches add instructions and memory traffic without adding parallelism. Software prefetching helps when the hardware cannot look ahead by itself, typically when walking a pointer-based structure whose upcoming addresses you know from elsewhere (for example, prefetching the hash buckets for a batch of incoming keys before probing them). The lesson generalises: performance folklore is a hypothesis until measured on your target hardware.
Worked example
lay out an order book level array
A book side holds up to 1000 price levels. The hot operation, on every tick, scans levels from best price outward until cumulative quantity reaches a target, reading only price (8 bytes) and qty (8 bytes). Each level also carries 48 bytes of cold data (order count, timestamps, venue flags). Currently it is std::map<int64_t, Level>. Propose a layout and estimate the bytes touched to scan 20 levels.
Show solutionHide solution
- Replace the node-based map with a contiguous array sorted by price (or indexed by tick offset from a reference price). A
std::mapnode is a separate allocation with three pointers, a colour flag and the key-value pair, so every step to the next level is a dependent pointer load, likely a cache miss in a long-lived book. - Split hot from cold. Keep
priceandqtyin a hot array (16 bytes per level, interleaved or as two columns), and the 48 bytes of cold data in a parallel array indexed the same way. - Bytes touched for 20 levels: hot data is bytes, five 64-byte lines (three 128-byte lines on the M1), all sequential so the prefetcher streams them. With the original 64-byte level struct in an array it would be bytes, 20 lines. With the map it is 20 or more scattered nodes, each potentially a ~100 ns miss: on the order of microseconds against tens of nanoseconds.
Inserting a level in the middle of an array costs an shift, but shifting a few kilobytes of contiguous memory is typically faster than one cache miss per map node, and most book updates change quantities at existing levels rather than inserting. State that trade-off; then say you would benchmark both on real tick data.
Knowledge check
Converting a loop from AoS to SoA barely changed its runtime: it sums one double field with a single accumulator. What is the most likely explanation?
Knowledge check
Why was summing the shuffled std::list about 100 times slower than the in-order list, even though both contain the same nodes at the same addresses?
Knowledge check
Two threads each increment their own std::atomic<long>, declared next to each other in one struct. What fix gave a roughly 3-4x speed-up in the benchmark?
Key takeaways
- Count bytes fetched, not operations: a loop reading 8 of every 64 bytes wastes seven-eighths of its bandwidth.
- First find the bottleneck. A dependent arithmetic chain can hide a layout win; independent accumulators expose it.
- Contiguous containers beat node-based ones by orders of magnitude once nodes are scattered (several hundred times here); dependent pointer chasing pays full memory latency per step.
- Separate data written by different threads onto different cache lines, using the real line size of the target CPU.
- Software prefetch is not a free win: on this machine it slowed a random gather. Benchmark every optimisation, report best-of-N and the range, and name the hardware.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).