Two ways to measure scaling
The objective of this lesson: split a computation across cores so that the answer is correct and reproducible, predict how far it will scale, and avoid the traps (false sharing, load imbalance, shared random streams) that make parallel code slower than serial.
Amdahl (fixed problem size). If a fraction of the serial run time parallelises perfectly over cores,
With : , , and the limit is 20.
Gustafson (fixed time, growing problem). In practice, more cores are used to run a bigger problem in the same time: more paths, more scenarios, more assets. If, on the -core machine, a fraction of the time is serial, the scaled speed-up is
With : and . The two laws do not contradict each other: Amdahl's is measured on one core for a fixed problem, Gustafson's on cores for a problem that grew. When an interviewer quotes Amdahl's ceiling, the useful reply is that Monte Carlo risk scales Gustafson-style: more cores buy more paths and a smaller standard error, not a shorter run of the same paths.
Work and span
Model a parallel algorithm as a graph of tasks. The work is the total number of operations (the time on one core). The span (also called depth or critical path) is the longest chain of dependent operations (the time on infinitely many cores). Then
- parallelism is : there is no point using more cores than this;
- a greedy scheduler achieves (Brent's bound), so when the speed-up is close to .
A parallel algorithm should be work-efficient (same as the best serial algorithm, up to a constant) with small span.
Reduction
Summing numbers serially has and . A tree of pairwise sums has the same work, additions, but span . For that is 20 levels instead of a million. On a CPU you do not build the full tree: each of threads sums a contiguous chunk serially, then the partial sums are combined. Requirements: the operation must be associative (integer addition, max, min; floating-point addition only approximately, so a parallel float sum may differ in the last bits from a serial one and from a run with a different ).
Prefix sum (scan)
The inclusive scan of is . It looks serial, but it parallelises in three phases with chunks:
- Each thread scans its own chunk and records the chunk total.
- Scan the chunk totals (small, serial is fine) to get each chunk's offset.
- Each thread adds its chunk's offset to every element of its chunk.
That is about work against serially, with span about . The tree version (Blelloch) has work and span . Scans are behind parallel cumulative P&L, running sums for VWAP, stream compaction (filtering) and radix sort.
Worked example
a blocked scan by hand
Compute the inclusive prefix sum of with two threads using the three-phase method.
Show solutionHide solution
Phase 1. Thread A scans to , total 9. Thread B scans to , total 22. Both run at the same time.
Phase 2. Exclusive scan of the totals gives offsets .
Phase 3. Thread A adds 0 (nothing to do). Thread B adds 9: .
Result: , which matches the serial running sum (). Thread B touched each of its elements twice, which is the extra work; in exchange, both halves ran in parallel.
A parallel reduction with std::thread
The program below sums for , serially and in parallel, and checks that every parallel result equals the serial one exactly (integer arithmetic, so the order of additions does not matter). Two partitioning schemes are compared: static (thread gets one contiguous chunk) and dynamic (threads repeatedly grab the next block of indices from an atomic counter).
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <thread>
#include <vector>
using u64 = std::uint64_t;
inline u64 f(u64 i) { return (i * i) % 1000003; } // some work per element
u64 serial_sum(u64 n) {
u64 s = 0;
for (u64 i = 0; i < n; ++i) s += f(i);
return s;
}
struct alignas(64) Slot { u64 v = 0; }; // one cache line per thread's result
// Static: thread t owns the contiguous chunk [n*t/T, n*(t+1)/T).
u64 sum_static(u64 n, unsigned T) {
std::vector<Slot> partial(T);
std::vector<std::thread> pool;
for (unsigned t = 0; t < T; ++t)
pool.emplace_back([&, t] {
u64 local = 0; // accumulate in a register, not in shared memory
for (u64 i = n * t / T; i < n * (t + 1) / T; ++i) local += f(i);
partial[t].v = local; // one write at the end
});
for (auto& th : pool) th.join(); // join orders the writes before our reads
u64 s = 0;
for (auto& p : partial) s += p.v;
return s;
}
// Dynamic: threads grab blocks from a shared counter; fast cores take more.
u64 sum_dynamic(u64 n, unsigned T, u64 block = 1 << 20) {
std::atomic<u64> next{0};
std::vector<Slot> partial(T);
std::vector<std::thread> pool;
for (unsigned t = 0; t < T; ++t)
pool.emplace_back([&, t] {
u64 local = 0;
for (u64 lo; (lo = next.fetch_add(block, std::memory_order_relaxed)) < n;)
for (u64 i = lo; i < std::min(lo + block, n); ++i) local += f(i);
partial[t].v = local;
});
for (auto& th : pool) th.join();
u64 s = 0;
for (auto& p : partial) s += p.v;
return s;
}
template <class F>
double time_ms(F fn, u64& out) {
auto t0 = std::chrono::steady_clock::now();
out = fn();
return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
}
int main() {
const u64 n = 400'000'000;
u64 ref, s;
double base = time_ms([&] { return serial_sum(n); }, ref);
std::printf("hardware threads %u, serial sum %llu in %.0f ms\n",
std::thread::hardware_concurrency(), (unsigned long long)ref, base);
for (unsigned T : {2u, 4u, 8u}) {
double a = time_ms([&] { return sum_static(n, T); }, s);
bool okA = s == ref;
double b = time_ms([&] { return sum_dynamic(n, T); }, s);
bool okB = s == ref;
std::printf("T=%u static %5.0f ms (%.1fx) %s dynamic %5.0f ms (%.1fx) %s\n", T, a,
base / a, okA ? "OK" : "BAD", b, base / b, okB ? "OK" : "BAD");
}
}
Built with c++ -std=c++20 -O2 -pthread, one run printed:
hardware threads 8, serial sum 199958623155600 in 278 ms
T=2 static 145 ms (1.9x) OK dynamic 144 ms (1.9x) OK
T=4 static 103 ms (2.7x) OK dynamic 90 ms (3.1x) OK
T=8 static 72 ms (3.9x) OK dynamic 70 ms (4.0x) OK
The total was also checked independently: is periodic in with period , and , so the sum is full periods plus a partial one, .
The timings are from one Apple M1 (4 performance and 4 efficiency cores) and are machine-specific. Over repeated runs the 8-thread speed-up ranged from about 2.8× to 4.7×, with dynamic often, but not always, ahead of static. The reasons it is not 8×:
- Unequal cores. The four efficiency cores are much slower. With static chunks, the run lasts as long as the slowest thread; dynamic blocks let the fast cores take more of the work.
- No pinning. macOS does not let a program pin threads to cores, so the scheduler may move threads or put two on one cluster. On Linux you would pin with
pthread_setaffinity_nportaskset. - Frequency. Laptop chips lower the clock when more cores are busy.
The design choices worth saying out loud in an interview: each thread accumulates into a local variable and writes its shared slot once; the slots are alignas(64) so that no two threads write the same cache line; and join provides the happens-before relation that makes reading the partials safe without atomics.
False sharing, measured
Two threads that write different variables on the same 64-byte cache line force the line to bounce between their cores' caches on every write. This program gives each of 4 threads its own counter and increments it times, with the counters packed (8 bytes apart) or padded (64 bytes apart):
#include <atomic>
#include <chrono>
#include <cstdio>
#include <thread>
#include <vector>
// Each thread increments only its OWN counter. No data is shared logically,
// yet adjacent counters share a cache line, which then bounces between cores.
struct Packed { std::atomic<long> v{0}; }; // 8 bytes: 8 per line
struct alignas(64) Padded { std::atomic<long> v{0}; }; // one per line
template <class C>
double run_ms(unsigned T, long iters) {
std::vector<C> c(T);
auto t0 = std::chrono::steady_clock::now();
std::vector<std::thread> pool;
for (unsigned t = 0; t < T; ++t)
pool.emplace_back([&, t] {
for (long i = 0; i < iters; ++i) c[t].v.fetch_add(1, std::memory_order_relaxed);
});
for (auto& th : pool) th.join();
long total = 0;
for (auto& x : c) total += x.v.load();
if (total != long(T) * iters) std::printf("wrong total\n");
return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
}
int main() {
const unsigned T = 4;
const long iters = 20'000'000;
std::printf("packed counters: %6.0f ms\n", run_ms<Packed>(T, iters));
std::printf("padded counters: %6.0f ms\n", run_ms<Padded>(T, iters));
}
Output on the same machine (machine-specific):
packed counters: 1141 ms
padded counters: 77 ms
About 14× from padding alone, with identical logic. (The atomics are there so the compiler cannot keep each counter in a register, which is exactly what the reduction above does deliberately with local.) C++17 also provides std::hardware_destructive_interference_size as a portable name for the padding size.
Parallel Monte Carlo with independent streams
Monte Carlo is the textbook parallel workload, and the textbook mistake is the random number generator:
- One shared generator behind a mutex serialises the program; without the mutex it is a data race.
- Seeding thread with
seed + tcan give correlated or overlapping streams for some generators. - Streams tied to threads make the answer depend on the thread count, so a result cannot be reproduced on a different machine.
The robust pattern: split the paths into a fixed number of blocks, give each block its own stream derived from (seed, block id), and let any number of threads process the blocks. Generators designed for this are counter-based (Philox and Threefry from Random123, used by cuRAND and NumPy) or generators with jump-ahead (xoshiro's jump(), MRG32k3a substreams).
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <random>
#include <thread>
#include <vector>
// Estimate pi by throwing points in the unit square. The work is split into
// fixed BLOCKS, each with its own random stream keyed by (seed, block id), so
// the answer does not depend on how many threads run the blocks.
constexpr int BLOCKS = 64;
constexpr std::uint64_t PER_BLOCK = 1'000'000;
std::uint64_t run_block(std::uint64_t seed, int block) {
std::seed_seq ss{seed, std::uint64_t(block)};
std::mt19937_64 rng(ss);
std::uniform_real_distribution<double> u(0.0, 1.0);
std::uint64_t hits = 0;
for (std::uint64_t k = 0; k < PER_BLOCK; ++k) {
double x = u(rng), y = u(rng);
hits += (x * x + y * y <= 1.0);
}
return hits;
}
std::uint64_t total_hits(std::uint64_t seed, unsigned T) {
std::vector<std::uint64_t> hits(BLOCKS); // one entry per block, written once
std::vector<std::thread> pool;
for (unsigned t = 0; t < T; ++t)
pool.emplace_back([&, t] {
for (int b = int(t); b < BLOCKS; b += int(T)) hits[b] = run_block(seed, b);
});
for (auto& th : pool) th.join();
std::uint64_t h = 0;
for (auto x : hits) h += x;
return h;
}
int main() {
const double N = double(BLOCKS) * double(PER_BLOCK);
for (unsigned T : {1u, 4u, 8u}) {
std::uint64_t h = total_hits(42, T);
double p = double(h) / N;
std::printf("T=%u hits=%llu pi~%.6f s.e.=%.6f\n", T, (unsigned long long)h, 4 * p,
4 * std::sqrt(p * (1 - p) / N));
}
}
Output:
T=1 hits=50260653 pi~3.141291 s.e.=0.000205
T=4 hits=50260653 pi~3.141291 s.e.=0.000205
T=8 hits=50260653 pi~3.141291 s.e.=0.000205
Identical hits for 1, 4 and 8 threads. The estimate is below , about 1.5 standard errors, which is unremarkable. The exact hit count depends on the standard library (uniform_real_distribution is not specified bit-for-bit), so another platform will print a different but equally reproducible number. Distinct seed_seq seeds for a Mersenne Twister make overlap astronomically unlikely in practice but not provably impossible; counter-based generators give that guarantee by construction.
The C++ toolbox
std::threadwith explicit partitioning, as above: full control, more code.- Parallel algorithms:
std::reduce(std::execution::par, v.begin(), v.end(), 0.0). With GCC's libstdc++ they need Intel TBB (-ltbb); with Apple's libc++ they needed-fexperimental-libraryon this machine, after which the call ran and summed halves to .par_unseqadditionally allows vectorisation, so the element function must not take locks. - OpenMP:
#pragma omp parallel for reduction(+ : s)above a loop, compiled with-fopenmp. The runtime handles threads, chunking (schedule(static)orschedule(dynamic, chunk)) and the reduction. A compiler without OpenMP ignores the pragma and runs the loop serially with the same result; Apple clang has no-fopenmp, so on this machine the snippet compiled and ran serially. - Thread pools / task systems (TBB, a hand-written pool with a work queue): create threads once, submit tasks. Creating a
std::threadcosts on the order of tens of microseconds, so per-task thread creation is wrong for fine-grained work. Work stealing (each worker has its own deque and steals from others when idle) is the standard way to balance irregular tasks.
Worked example
how many paths for a standard error, and how long?
A Monte Carlo price has per-path standard deviation 12 (in price units). Risk wants a standard error of 0.01. One core simulates paths per second. Profiling shows 2 s of serial setup (loading curves and the trade) regardless of path count, and path simulation parallelises perfectly. How long does the job take on 1 core and on 32 cores, and what is the speed-up?
Show solutionHide solution
Paths. The standard error is , so paths.
One core. Simulation: s. Total s.
32 cores. Simulation: s. Total s. Speed-up .
Here the parallel fraction is only , and Amdahl's ceiling is , which 32 cores have essentially reached. The useful observation: parallelise or cache the setup, not the paths. If instead risk wants the error 10× smaller, grows 100× to paths, simulation takes 28.8 s on one core and 0.9 s on 32 cores, and parallelism pays: ×. That is Gustafson's point: the benefit of more cores grows with the problem.
Knowledge check
A parallel sum of 1,000 doubles gives a result that differs in the 15th significant digit from the serial loop, and changes again with a different thread count. What is the best explanation?
Knowledge check
An algorithm has work operations and span . Using Brent's bound , about what speed-up can you expect on 64 cores?
Knowledge check
You parallelise a Monte Carlo pricer by giving each thread its own generator seeded with the thread id. What is the main problem?
Key takeaways
- Amdahl: fixed problem, . Gustafson: problem grows with cores, . Monte Carlo usually scales the Gustafson way.
- Work and span: aim for work-efficient algorithms with . Reduction has span ; a blocked scan costs about work.
- Accumulate locally, write shared results once, pad per-thread data to 64 bytes. False sharing cost 14× in the measured example.
- Use dynamic scheduling when cores or tasks are unequal; static chunks run as slowly as the slowest thread.
- Give random streams to fixed blocks of work, not to threads, and use generators built for independent streams.
- Always verify the parallel result against a serial reference before timing it.
Practice problems
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).