Skip to content
LeetQuant
E11 High-Performance Computing

E11 · High-Performance Computing · Lesson 3 of 4

Parallel Algorithms

Amdahl and Gustafson scaling, work and span, parallel reduction and prefix sum, Monte Carlo with independent random streams, false sharing, and the C++ tools (std::thread, std::execution, OpenMP, thread pools), with measured multi-core runs.

20 min

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 ff of the serial run time parallelises perfectly over pp cores,

SAmdahl(p)=1(1−f)+f/p.S_{\text{Amdahl}}(p) = \frac{1}{(1 - f) + f / p}.

With f=0.95f = 0.95: S(8)≈5.93S(8) \approx 5.93, S(64)≈15.4S(64) \approx 15.4, 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 pp-core machine, a fraction 1−f1 - f of the time is serial, the scaled speed-up is

SGustafson(p)=(1−f)+fp.S_{\text{Gustafson}}(p) = (1 - f) + f p.

With f=0.95f = 0.95: S(8)=7.65S(8) = 7.65 and S(64)=60.85S(64) = 60.85. The two laws do not contradict each other: Amdahl's ff is measured on one core for a fixed problem, Gustafson's on pp 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 WW is the total number of operations (the time on one core). The span DD (also called depth or critical path) is the longest chain of dependent operations (the time on infinitely many cores). Then

  • parallelism is W/DW / D: there is no point using more cores than this;
  • a greedy scheduler achieves Tp≤W/p+DT_p \le W / p + D (Brent's bound), so when W/p≫DW / p \gg D the speed-up is close to pp.

A parallel algorithm should be work-efficient (same WW as the best serial algorithm, up to a constant) with small span.

Reduction

Summing nn numbers serially has W=n−1W = n - 1 and D=n−1D = n - 1. A tree of pairwise sums has the same work, n−1n - 1 additions, but span ⌈log⁡2n⌉\lceil \log_2 n \rceil. For n=220n = 2^{20} that is 20 levels instead of a million. On a CPU you do not build the full tree: each of TT threads sums a contiguous chunk serially, then the TT 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 TT).

Prefix sum (scan)

The inclusive scan of xx is yi=x0+⋯+xiy_i = x_0 + \dots + x_i. It looks serial, but it parallelises in three phases with TT chunks:

  1. Each thread scans its own chunk and records the chunk total.
  2. Scan the TT chunk totals (small, serial is fine) to get each chunk's offset.
  3. Each thread adds its chunk's offset to every element of its chunk.

That is about 2n2n work against nn serially, with span about 2n/T+T2n / T + T. The tree version (Blelloch) has work 2(n−1)2(n - 1) and span 2log⁡2n2 \log_2 n. 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 x=[3,1,4,1,5,9,2,6]x = [3, 1, 4, 1, 5, 9, 2, 6] with two threads using the three-phase method.

Show solution

Phase 1. Thread A scans [3,1,4,1][3, 1, 4, 1] to [3,4,8,9][3, 4, 8, 9], total 9. Thread B scans [5,9,2,6][5, 9, 2, 6] to [5,14,16,22][5, 14, 16, 22], total 22. Both run at the same time.

Phase 2. Exclusive scan of the totals [9,22][9, 22] gives offsets [0,9][0, 9].

Phase 3. Thread A adds 0 (nothing to do). Thread B adds 9: [14,23,25,31][14, 23, 25, 31].

Result: [3,4,8,9,14,23,25,31][3, 4, 8, 9, 14, 23, 25, 31], which matches the serial running sum (3+1+4+1+5+9+2+6=313 + 1 + 4 + 1 + 5 + 9 + 2 + 6 = 31). 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 f(i)=i2 mod 1,000,003f(i) = i^2 \bmod 1{,}000{,}003 for i<4×108i < 4 \times 10^8, 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 tt gets one contiguous chunk) and dynamic (threads repeatedly grab the next block of 2202^{20} 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: i2 mod pi^2 \bmod p is periodic in ii with period p=1,000,003p = 1{,}000{,}003, and 4×108=399p+998,8034 \times 10^8 = 399p + 998{,}803, so the sum is 399399 full periods plus a partial one, 199,958,623,155,600199{,}958{,}623{,}155{,}600.

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_np or taskset.
  • 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 2×1072 \times 10^7 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 tt with seed + t can 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 0.0003020.000302 below π\pi, 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::thread with 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-library on this machine, after which the call ran and summed 10710^7 halves to 5,000,000.05{,}000{,}000.0. par_unseq additionally 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) or schedule(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::thread costs 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 5×1065 \times 10^6 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 solution

Paths. The standard error is σ/N\sigma / \sqrt{N}, so N=(σ/s.e.)2=(12/0.01)2=12002=1,440,000N = (\sigma / \text{s.e.})^2 = (12 / 0.01)^2 = 1200^2 = 1{,}440{,}000 paths.

One core. Simulation: 1.44×106/5×106=0.2881.44 \times 10^6 / 5 \times 10^6 = 0.288 s. Total 2+0.288=2.2882 + 0.288 = 2.288 s.

32 cores. Simulation: 0.288/32=0.0090.288 / 32 = 0.009 s. Total 2.0092.009 s. Speed-up 2.288/2.009≈1.142.288 / 2.009 \approx 1.14.

Here the parallel fraction is only f=0.288/2.288≈0.126f = 0.288 / 2.288 \approx 0.126, and Amdahl's ceiling is 1/(1−f)≈1.141 / (1 - f) \approx 1.14, 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, NN grows 100× to 1.44×1081.44 \times 10^8 paths, simulation takes 28.8 s on one core and 0.9 s on 32 cores, and parallelism pays: 30.8/2.9≈10.630.8 / 2.9 \approx 10.6×. 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 W=109W = 10^9 operations and span D=103D = 10^3. Using Brent's bound Tp≤W/p+DT_p \le W / p + D, 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, S≤1/(1−f)S \le 1 / (1 - f). Gustafson: problem grows with cores, S=(1−f)+fpS = (1 - f) + f p. Monte Carlo usually scales the Gustafson way.
  • Work and span: aim for work-efficient algorithms with W/p≫DW / p \gg D. Reduction has span log⁡2n\log_2 n; a blocked scan costs about 2n2n 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).