Computer Science · Book 5 · Bachelor Year 3

University Computer Science — Year 3

University Computer Science — Year 3 · Bachelor Year 3

24Parallel Programming

A laptop has many cores, and a program that uses one of them leaves the others idle. Splitting the work is easy to start and hard to finish: the parts must not interfere, the time spent splitting and joining must stay small, and some steps cannot be split at all. This chapter measures what a split gains on the laptop, proves the two laws that bound it, models a computation as a graph whose total size and longest path decide how fast any number of processors can run it, and builds the parallel prefix sum, a small algorithm that looks sequential and is not. Along the way the Rust compiler refuses a data race, two threads slow each other down without sharing a single variable, and the C compiler turns one loop into instructions that add four numbers at once.

You already know

The threads of a process share its memory and run interleaved, in an order nobody controls; a data race is two unsynchronised accesses to one location by two threads, at least one a write. A cache keeps recently used memory in lines of 64 bytes close to the processor (Year 2 volume). Divide and conquer splits a problem into smaller ones of the same kind, and its cost satisfies a recurrence such as T(n)=2T(n/2)+nT(n) = 2T(n/2) + n, whose solution is Θ(nlog⁡n)\Theta(n \log n) (Year 1 volume). A scoped thread in Rust may borrow from the function that spawned it, because the scope waits for it before returning.

24.1 Speed-up and its limits

Definition 24.1 (Speed-up, efficiency)

Let T1T_1 be the time of a computation on one processor and TpT_p its time on pp processors. Its speed-up on pp processors is Sp=T1/TpS_p = T_1 / T_p, and its efficiency is Ep=Sp/pE_p = S_p / p. A speed-up of pp, efficiency 1, is linear.

The first program splits two jobs over pp scoped threads. One adds 2252^{25} numbers, a job of one addition per number read from memory; the other runs a loop of shifts and exclusive ors on as many numbers, a job of 120 shift-and-xor steps, 240 operations, per number that touches no memory at all.

fn sum_mem(data: &[u32], p: usize) -> u64 {
    let chunk = data.len().div_ceil(p);
    thread::scope(|s| {
        let parts: Vec<_> = data
            .chunks(chunk)
            .map(|c| s.spawn(move || c.iter().map(|&v| v as u64).sum::<u64>()))
            .collect();
        parts.into_iter().map(|h| h.join().unwrap()).sum()
    })
}

fn sum_cpu(n: u64, p: u64) -> u64 {
    thread::scope(|s| {
        let parts: Vec<_> = (0..p)
            .map(|t| {
                s.spawn(move || {
                    (t * n / p..(t + 1) * n / p)
                        .map(mix)
                        .fold(0, u64::wrapping_add)
                })
            })
            .collect();
        parts
            .into_iter()
            .map(|h| h.join().unwrap())
            .fold(0, u64::wrapping_add)
    })
}
Listing 24.1. Each job cut into pp chunks, one scoped thread per chunk; the partial results are added after the threads are joined. code/bachelor-3/24-parallel-programming/listings/sum_threads.rs
$ rustc --edition 2021 -O -o sum_threads sum_threads.rs && ./sum_threads
 p   memory-bound ms  speed-up   compute-bound ms  speed-up
 1             10.4      1.00              454.4      1.00
 2              5.9      1.77              230.6      1.97
 3              4.3      2.42              156.3      2.91
 4              3.7      2.82              119.6      3.80
 5              3.4      3.06              100.7      4.51
 6              3.4      3.06               92.4      4.92
 7              3.1      3.33               87.3      5.21
 8              2.9      3.57               80.3      5.66
Output 24.1. One run on the author’s laptop, best of five for each pp: the memory-bound sum stops near 3.5, the compute-bound loop reaches between 5 and 6.

Neither job reaches 8. The compute-bound loop shares nothing, so its losses do not come from communication. Creating and joining eight threads costs microseconds, nothing against a run of 80 ms. The likelier causes are in the machine: the program gives every thread an equal chunk, but the laptop’s processor mixes fast and slower cores, so the slowest thread decides when the job ends; cores also run at lower clock speeds when more of them are busy, and other programs share them. The curve bends after p=4p = 4, as these causes predict. The memory-bound sum stops earlier for a different reason, which no number of cores fixes: the cores share the path to memory, and a few of them already read as fast as it delivers.

Every program also has parts that do not split. If a fraction ff of its time on one processor is sequential, the rest gains at most pp.

Theorem 24.2 (Amdahl’s law)

If a fraction ff of a computation’s time on one processor must run sequentially and the rest divides perfectly among pp processors, its speed-up is Sp=1/(f+(1−f)/p)S_p = 1 / (f + (1 - f)/p), which increases with pp towards 1/f1/f and never reaches it.

Proof. With T1=1T_1 = 1, the sequential part takes ff on any number of processors, and the rest takes (1−f)/p(1 - f)/p, so Tp=f+(1−f)/pT_p = f + (1 - f)/p and Sp=1/(f+(1−f)/p)S_p = 1 / (f + (1 - f)/p). As pp grows the denominator decreases strictly towards f>0f > 0, so SpS_p increases strictly towards 1/f1/f without reaching it. ∎

The law was presented by Gene Amdahl at a conference of 1967. Its lesson is severe: with 5 % of sequential work, a million processors give less than 20.

Amdahl’s law for four sequential fractions. With 1 % of sequential work, 64 processors give 39; with 20 %, they give 4.7, and no number of processors gives 5.
Amdahl’s law for four sequential fractions. With 1 % of sequential work, 64 processors give 39; with 20 %, they give 4.7, and no number of processors gives 5.

Amdahl’s law keeps the problem fixed. In practice a larger machine is used for a larger problem, whose parallel part grows while its sequential part stays the same, and the question becomes how much more work fits in the same time.

Theorem 24.3 (Gustafson’s law)

If a run on pp processors spends a fraction ff of its time in sequential work and the rest with all pp processors busy, the same computation takes f+(1−f)pf + (1 - f)p times longer on one processor: its scaled speed-up is p−f(p−1)p - f(p - 1).

Proof. Take the parallel run’s time as 1. Its sequential part takes ff on one processor as well. Its parallel part keeps pp processors busy for 1−f1 - f, which is (1−f)p(1 - f)p processor-time units, and one processor needs that long to do it. So T1=f+(1−f)pT_1 = f + (1 - f)p and T1/Tp=f+(1−f)p=p−f(p−1)T_1 / T_p = f + (1 - f)p = p - f(p - 1). ∎

The law is named after John Gustafson and his colleague Edwin Barsis; Gustafson presented it in 1988 in an article titled Reevaluating Amdahl’s law. The two laws do not contradict each other: they answer different questions. With f=10 %f = 10\,\% measured on 8 processors, Gustafson’s scaled speed-up is 7.3, while Amdahl’s law with f=10 %f = 10\,\% measured on one processor gives 4.7.

A speed-up can even exceed pp. When a job’s data do not fit in one core’s cache but its pp parts fit in pp caches, each part runs from its cache and the whole runs faster than pp times the original: the superlinear speed-up comes from more cache, not from more processors.

24.2 Task and data parallelism

Definition 24.4 (Task parallelism, data parallelism, fork–join)

Data parallelism applies the same operation to different parts of the data at once, as the chunks of Listing 24.1. Task parallelism runs different computations at once, such as the two recursive calls of a sort. In the fork–join pattern, a computation forks into parts that run in parallel and continues only when all of them have finished, at the join.

A recursive merge sort is fork–join: the two halves are sorted in parallel, then merged. The C program below forks a thread at each of the top log⁡2p\log_2 p levels of the recursion with POSIX threads, and joins it before the merge.

static void *sort(void *arg)
{
    job *w = arg;
    if (w->n < 2) return NULL;
    size_t h = w->n / 2;
    job left = {w->a, w->tmp, h, w->threads / 2};
    job right = {w->a + h, w->tmp + h, w->n - h, w->threads - w->threads / 2};
    if (w->threads > 1) { /* fork: the left half on a new thread, the right here */
        pthread_t t;
        pthread_create(&t, NULL, sort, &left);
        sort(&right);
        pthread_join(t, NULL); /* join */
    } else {
        sort(&left);
        sort(&right);
    }
    merge(w->a, w->tmp, w->n);
    return NULL;
}
Listing 24.2. Fork the left half onto a new thread while this one sorts the right half; join, then merge. code/bachelor-3/24-parallel-programming/listings/psort.c
$ gcc -std=c17 -O2 -Wall -Wextra -o psort psort.c -lm && ./psort
 p  time ms  speed-up
 1   1354.2      1.00
 2    716.2      1.89
 4    418.5      3.24
 8    303.1      4.47
Output 24.2. Sorting 2242^{24} integers on the author’s laptop, best of three: 4.5 with 8 threads.

Each thread sorts its own range of the array, so no two threads write the same element. In C, nothing checks it. In Rust, the borrow checker does: a scoped thread may hold a mutable reference only if no other thread holds a reference to the same data, which is exactly the absence of data races.

fn main() {
    let mut count = 0u64;
    thread::scope(|s| {
        s.spawn(|| {
            for _ in 0..1000 {
                count += 1;
            }
        });
        s.spawn(|| {
            for _ in 0..1000 {
                count += 1;
            }
        });
    });
    println!("{count}");
}
Listing 24.3. Two threads adding to one counter: a data race, written in Rust. code/bachelor-3/24-parallel-programming/listings/race_reject.rs
$ rustc --edition 2021 -O -o race_reject race_reject.rs && ./race_reject
error[E0499]: cannot borrow `count` as mutable more than once at a time
   --> race_reject.rs:14:17
    |
  8 |       thread::scope(|s| {
    |                      - has type `&'1 Scope<'1, '_>`
  9 |           s.spawn(|| {
    |           -       -- first mutable borrow occurs here
    |  _________|
    | |
 10 | |             for _ in 0..1000 {
 11 | |                 count += 1;
    | |                 ----- first borrow occurs due to use of `count` in closure
 12 | |             }
 13 | |         });
    | |__________- argument requires that `count` is borrowed for `'1`
 14 |           s.spawn(|| {
    |                   ^^ second mutable borrow occurs here
 15 |               for _ in 0..1000 {
 16 |                   count += 1;
    |                   ----- second borrow occurs due to use of `count` in closure
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0499`.
[exit status 1]
Output 24.3. The compiler’s refusal, a staged error: the counter cannot be borrowed mutably by two threads at once. A note pointing into the standard library is left out. Some lines are left out.

The program is fixed by giving each thread its own counter and adding them after the join, as sum_threads.rs does, or by an atomic counter or a mutex; all three compile.

24.3 Work and span

A parallel program’s running time depends on how many processors run it and how they are scheduled. Two numbers of the computation itself bound it whatever the machine.

Definition 24.5 (Work, span, parallelism)

A computation is modelled as a directed acyclic graph, its DAG: one node per operation, taking unit time, and an edge from each operation to every operation that uses its result. The work WW of the computation, also written T1T_1, is its number of nodes; its span SS, also written T∞T_\infty, is the number of nodes on a longest path, its critical path. Its parallelism is the ratio W/SW / S.

One processor runs one node per step, so it needs WW steps; infinitely many still need SS, since the nodes of a path run one after the other. On pp processors, therefore, Tp≥W/pT_p \ge W/p (the work law) and Tp≥ST_p \ge S (the span law). The parallelism is the largest speed-up the computation allows: T1/Tp≤W/ST_1 / T_p \le W / S.

The DAG of merge sort on four elements, each merge a chain of one step per element it outputs. Work 8, span 6; the shaded critical path runs through one of the two small merges, then the whole final merge.
The DAG of merge sort on four elements, each merge a chain of one step per element it outputs. Work 8, span 6; the shaded critical path runs through one of the two small merges, then the whole final merge.

The program below builds the DAGs of the chapter’s algorithms node by node and measures them.

def work_span(preds):
    """preds: node -> the nodes it depends on (a DAG)."""

    @cache
    def depth(v):
        return 1 + max((depth(u) for u in preds[v]), default=0)

    return len(preds), max(depth(v) for v in preds)
Listing 24.4. Work counts the nodes; span is the largest depth, each node one deeper than its deepest input. code/bachelor-3/24-parallel-programming/listings/workspan.py
$ python workspan.py
algorithm                      n    work  span  parallelism
sum (reduction)                8       7     3          2.3
sum (reduction)             1024    1023    10        102.3
Hillis-Steele scan             8      17     3          5.7
Hillis-Steele scan          1024    9217    10        921.7
Blelloch scan                  8      14     5          2.8
Blelloch scan               1024    2046    19        107.7
merge sort, serial merge       8      24    14          1.7
merge sort, serial merge    1024   10240  2046          5.0
Output 24.4. Work, span and parallelism of four DAGs. The merge sort’s sequential merges cap its parallelism at 5 for 1,024 elements.

A schedule decides which ready nodes run at each step; a node is ready when all its inputs have run.

Definition 24.6 (Greedy scheduler, work stealing)

A greedy scheduler on pp processors never leaves a processor idle while a node is ready: at each step it runs min⁡(p,r)\min(p, r) of the rr ready nodes. Under work stealing, each processor keeps a queue of the tasks it has forked and works from it; a processor whose queue is empty takes a task from the queue of another, chosen at random.

Theorem 24.7 (Brent’s theorem)

A greedy scheduler runs a computation of work WW and span SS on pp processors in Tp≤W/p+ST_p \le W/p + S steps. Since every schedule needs at least max⁡(W/p,S)\max(W/p, S) steps, a greedy schedule takes at most twice as long as the best one.

Proof. Call a step complete if it runs pp nodes, incomplete otherwise. Each complete step runs pp of the WW nodes, so there are at most W/pW/p complete steps. In an incomplete step, the greedy scheduler runs every ready node. Let GG be the DAG of the nodes not yet run; its sources are exactly the ready nodes, and every longest path of GG starts at a source, since a longest path that started below a node would extend to it. Running all the sources shortens every longest path of GG by its first node, so each incomplete step decreases the span of GG by one, and there are at most SS of them. Hence Tp≤W/p+ST_p \le W/p + S. Every schedule takes at least W/pW/p steps and at least SS steps, so the best one takes Tp∗≥max⁡(W/p,S)T^*_p \ge \max(W/p, S), and W/p+S≤2max⁡(W/p,S)≤2Tp∗W/p + S \le 2\max(W/p, S) \le 2T^*_p. ∎

The theorem goes back to Richard Brent’s paper of 1974 on evaluating arithmetic expressions in parallel. The program below schedules two DAGs greedily and compares the result with both bounds.

def greedy(preds, p):
    """Steps taken by a greedy schedule, ready nodes taken oldest first."""
    waiting = {v: len(us) for v, us in preds.items()}
    users = {v: [] for v in preds}
    for v, us in preds.items():
        for u in us:
            users[u].append(v)
    ready = [v for v, k in waiting.items() if k == 0]
    steps = 0
    while ready:
        run, ready = ready[:p], ready[p:]
        for u in run:
            for v in users[u]:
                waiting[v] -= 1
                if waiting[v] == 0:
                    ready.append(v)
        steps += 1
    return steps
Listing 24.5. A greedy scheduler: at each step it runs up to pp ready nodes, then counts down the inputs their users still wait for. code/bachelor-3/24-parallel-programming/listings/brent.py
$ python brent.py
random DAG: work W = 2000, span S = 214
 p    T_p  max(W/p, S)  W/p + S  T_p / lower bound
 1   2000         2000     2214               1.00
 2   1000         1000     1214               1.00
 3    667          667      881               1.00
 4    501          500      714               1.00
 5    402          400      614               1.00
 6    338          334      547               1.01
 7    296          286      500               1.03
 8    266          250      464               1.06
merge sort of 256: work W = 2048, span S = 510
 p    T_p  max(W/p, S)  W/p + S  T_p / lower bound
 1   2048         2048     2558               1.00
 2   1152         1024     1534               1.12
 3    896          683     1193               1.31
 4    768          512     1022               1.50
 5    704          510      920               1.38
 6    662          510      851               1.30
 7    631          510      803               1.24
 8    608          510      766               1.19
Output 24.5. A random DAG of 2,000 nodes and the merge sort of 256 elements, on 1 to 8 processors. Every time lies between the lower bound and Brent’s bound; the worst ratio, 1.5, is the merge sort on 4 processors.

On the random DAG, whose parallelism is above 9, the greedy schedule is almost perfect for up to 8 processors. On the merge sort, parallelism 4, the final merges leave processors idle, and adding them beyond 4 helps little. A real runtime does not see the DAG in advance: tasks appear as the program forks them. Work stealing balances them as they appear; Blumofe and Leiserson proved in 1999 that it runs a well-structured fork–join computation in expected time W/p+O(S)W/p + O(S), close to Brent’s bound.

24.4 Parallel algorithms

Definition 24.8 (Parallel reduction, prefix sum)

A parallel reduction combines nn values with an associative operation, such as ++ or max⁡\max, by a tree of combinations: work n−1n - 1, span ⌈log⁡2n⌉\lceil \log_2 n \rceil. The prefix sum, or scan, of a0,…,an−1a_0, \ldots, a_{n-1} is the sequence of running totals: inclusive, a0+⋯+aia_0 + \cdots + a_i at position ii, or exclusive, a0+⋯+ai−1a_0 + \cdots + a_{i-1}, which starts with 0.

Associativity is what allows the tree: (a+b)+(c+d)(a + b) + (c + d) equals ((a+b)+c)+d((a + b) + c) + d, so the pairs can be added at the same time. Floating-point addition is not exactly associative, and a parallel sum of floats may differ in its last digits from the sequential one; the programs of this chapter add integers.

A scan looks sequential: each total needs the one before it. Hillis and Steele gave in 1986 a scan of span log⁡2n\log_2 n, in which every element adds the one 2d2^d places to its left in round dd; it does nlog⁡2n−(n−1)n \log_2 n - (n - 1) additions instead of n−1n - 1. Blelloch’s scan does 2(n−1)2(n - 1), in a tree.

/// Exclusive scan in place (n a power of two): an up-sweep builds a tree of partial
/// sums, a down-sweep pushes the sums of the left subtrees down to the right.
pub fn blelloch(x: &mut [i64], trace: bool) -> (u64, u32) {
    let (n, mut work, mut span) = (x.len(), 0, 0);
    let mut d = 1;
    while d < n {
        for i in (2 * d - 1..n).step_by(2 * d) {
            x[i] += x[i - d];
            work += 1;
        }
        span += 1;
        if trace {
            println!("up   {d}: {x:?}");
        }
        d *= 2;
    }
    x[n - 1] = 0;
    while d > 1 {
        d /= 2;
        for i in (2 * d - 1..n).step_by(2 * d) {
            let left = x[i - d];
            x[i - d] = x[i];
            x[i] += left;
            work += 1;
        }
        span += 1;
        if trace {
            println!("down {d}: {x:?}");
        }
    }
    (work, span)
}
Listing 24.6. Blelloch’s exclusive scan: the up-sweep leaves the sum of each subtree at its right end, the down-sweep hands each left subtree the total before it and each right subtree that total plus the left sum. code/bachelor-3/24-parallel-programming/listings/scan.rs
$ rustc --edition 2021 -O -o scan scan.rs && ./scan
rain:   [0, 62, 0, 29, 8, 34, 0, 0]
up   1: [0, 62, 0, 29, 8, 42, 0, 0]
up   2: [0, 62, 0, 91, 8, 42, 0, 42]
up   4: [0, 62, 0, 91, 8, 42, 0, 133]
down 4: [0, 62, 0, 0, 8, 42, 0, 91]
down 2: [0, 0, 0, 62, 8, 91, 0, 133]
down 1: [0, 0, 62, 62, 91, 99, 133, 133]
     n   Hillis-Steele work span   Blelloch work span
     16                  49    4                 30    8
    256                1793    8                510   16
   4096               45057   12               8190   24
  65536              983041   16             131070   32
1048576            19922945   20            2097150   40
Output 24.6. The scan traced on eight days of rain, then the counted additions and rounds of both scans: Blelloch’s does twice the minimum work, Hillis and Steele’s about log⁡2n−1\log_2 n - 1 times as much.
Blelloch’s scan on the rain of eight days, in tenths of a millimetre, row by row as scan.rs prints it; shaded cells written in that round, even when the value stays the same. After the up-sweep the last cell holds the total, 133; it is replaced by 0 and the down-sweep ends with the exclusive running totals.
Blelloch’s scan on the rain of eight days, in tenths of a millimetre, row by row as scan.rs prints it; shaded cells written in that round, even when the value stays the same. After the up-sweep the last cell holds the total, 133; it is replaced by 0 and the down-sweep ends with the exclusive running totals.

Theorem 24.9 (Blelloch’s scan)

For n=2kn = 2^k, Blelloch’s scan computes the exclusive prefix sums with 2(n−1)2(n - 1) additions in 2k2k rounds, the additions of each round being independent.

Proof. View positions 0,…,n−10, \ldots, n - 1 as the leaves of a complete binary tree; a node of height hh covers 2h2^h consecutive positions and is stored at the last of them. Up-sweep. In round d=2h−1d = 2^{h-1}, position ii adds position i−di - d: it then holds the sum of its node’s left child (stored at i−di - d) and right child (stored at ii), by induction on hh. The positions written in one round are distinct and none is read by another addition of the round, so the additions are independent. Round dd does n/(2d)n/(2d) additions, n/2+n/4+⋯+1=n−1n/2 + n/4 + \cdots + 1 = n - 1 in all, in kk rounds. Down-sweep. Claim: when the down-sweep reaches height hh, the position of each node of height hh holds the sum of all positions before the node. It holds at the root, set to 0. At a node with that value vv stored at ii, whose left child is stored at i−di - d and still holds the left sum ℓ\ell from the up-sweep, the round writes vv at i−di - d and v+ℓv + \ell at ii: exactly the sums before the left and the right child. At height 0 every position holds the sum before it. The down-sweep, too, does n−1n - 1 independent additions in kk rounds. ∎

The DAG of workspan.py finds a span of 2k−12k - 1, one less than the 2k2k rounds: the root’s sum, computed by the last addition of the up-sweep, is replaced by 0, so no path runs through it into the down-sweep.

A scan on pp processors does not need a tree of nn leaves. The blocked scan of the weekend problem cuts the array into pp blocks: each processor sums its block, the pp sums are scanned, and each processor scans its block again from the total before it; exercise 24.11 analyses it.

Parallel threads can also slow each other down without sharing data. A cache works in lines of 64 bytes, and a core must hold a line on its own to write it; two cores writing two different variables of one line pass the line back and forth.

Definition 24.10 (False sharing)

False sharing occurs when threads on different cores repeatedly write different variables that lie in the same cache line: the line moves between the cores’ caches at every write, though no variable is shared.

#define MAXP 8

struct padded { _Alignas(64) atomic_long v; };
static _Alignas(64) atomic_long packed[MAXP]; /* eight counters in one 64-byte line */
static struct padded spread[MAXP];            /* one counter per line */

static void *bump(void *arg)
{
    atomic_long *c = arg;
    for (long i = 0; i < STEPS; i++)
        atomic_fetch_add_explicit(c, 1, memory_order_relaxed);
    return NULL;
}
Listing 24.7. Eight counters in one 64-byte line, or eight in eight lines; each thread adds to its own counter only. code/bachelor-3/24-parallel-programming/listings/false_sharing.c
$ gcc -std=c17 -O2 -Wall -Wextra -o false_sharing false_sharing.c -lm && ./false_sharing
 p  adjacent ms  padded ms  ratio
 1        191.3      194.5    1.0
 2        762.5      195.8    3.9
 4       2507.4      208.1   12.0
 8       5832.6      351.5   16.6
all counts correct: yes
Output 24.7. One run on the author’s laptop, best of three: with 8 threads, the adjacent counters are about 17 times slower than the padded ones.

With one thread the two layouts take the same time. With 8, each thread does the same work as alone, yet the adjacent counters take more than 30 times longer than with one thread, while the padded ones take less than twice as long. The fix is the padding of struct padded: one counter per line.

24.5 Vector instructions and accelerators

Parallelism also lives inside one core.

Definition 24.11 (SIMD, vectorisation)

A SIMD instruction (single instruction, multiple data) applies one operation to several values held side by side in a wide register, its lanes: a 16-byte register holds four 32-bit floats. Vectorisation is the compiler’s rewriting of a loop so that each instruction processes several iterations, one per lane.

A loop can be vectorised only if running several iterations at once gives the same result as running them in order. GCC reports what it did when asked.

/* saxpy.c -- y = a x + y over n floats, and a running sum over n floats. */
void saxpy(int n, float a, const float *restrict x, float *restrict y)
{
    for (int i = 0; i < n; i++)
        y[i] = a * x[i] + y[i];
}

void running_sum(int n, float *y)
{
    for (int i = 1; i < n; i++)
        y[i] = y[i] + y[i - 1];
}
Listing 24.8. Two loops over floats: each iteration of the first is independent, each iteration of the second needs the one before. code/bachelor-3/24-parallel-programming/listings/saxpy.c
$ gcc -O3 -fopt-info-vec-optimized -c saxpy.c
saxpy.c:4:23: optimized: loop vectorized using 16 byte vectors
saxpy.c:4:23: optimized: loop vectorized using 8 byte vectors
$ gcc -O3 -fopt-info-vec-missed -c saxpy.c 2>&1 | grep -E '^saxpy.c:1[01]'
saxpy.c:10:23: missed: couldn't vectorize loop
saxpy.c:11:24: missed: not vectorized, possible dependence between data-refs *_6 and *_3
$ gcc -O3 -S -o - saxpy.c | grep -E 'mulps|addps|mulss|addss'
	mulps	%xmm2, %xmm1
	addps	%xmm3, %xmm1
	mulps	%xmm2, %xmm1
	addps	%xmm2, %xmm1
	mulss	(%rcx,%rax,4), %xmm0
	addss	(%rdx), %xmm0
	addss	(%rax), %xmm0
Output 24.8. The compiler vectorises the first loop with 16-byte vectors, and its remainder with 8-byte ones, but not the running sum. The assembly shows packed instructions (ps, four floats each) and scalar ones (ss, one float).

The restrict qualifiers promise that x and y do not overlap; without them the compiler would have to check at run time that a write to y cannot change a later x[i]. The running sum is a scan, and its dependency of distance one keeps every lane waiting for the one before.

A Cray-1 in the Deutsches Museum, Munich (photograph by Clemens Pfeiffer, 2006, CC BY 2.5). Designed by Seymour Cray and first installed at Los Alamos in 1976, it was the first supercomputer to implement the vector processor design successfully, at a peak of 160 million floating-point operations per second; eighty were sold. The benches around its base cover the power supplies.
A Cray-1 in the Deutsches Museum, Munich (photograph by Clemens Pfeiffer, 2006, CC BY 2.5). Designed by Seymour Cray and first installed at Los Alamos in 1976, it was the first supercomputer to implement the vector processor design successfully, at a peak of 160 million floating-point operations per second; eighty were sold. The benches around its base cover the power supplies.

A graphics processor, or GPU, takes the same idea much further: thousands of lanes grouped into many cores, each group running one instruction on many data, with its own memory hierarchy between the lanes and the main memory. It suits data parallelism on large arrays, the matrix products of neural networks above all; the One Artificial Intelligence Book and One Quant Book series return to it at length.

24.6 Exercises

Exercise 24.1 ★

A program spends 10 % of its single-processor time in sequential work. What speed-up does Amdahl’s law give on 8 processors, and what is its limit? What sequential fraction would allow a speed-up of 6 on 8 processors?

Solution

Solution of Exercise 24.1.

S8=1/(0.1+0.9/8)=1/0.2125≈4.71S_8 = 1 / (0.1 + 0.9/8) = 1/0.2125 \approx 4.71, and the limit is 1/0.1=101/0.1 = 10. A speed-up of 6 on 8 processors needs f+(1−f)/8=1/6f + (1 - f)/8 = 1/6, so 7f/8=1/6−1/8=1/247f/8 = 1/6 - 1/8 = 1/24 and f=1/21≈4.8 %f = 1/21 \approx 4.8\,\%.

Exercise 24.2 ★

Draw the DAG of the evaluation of (a+b)(c+d)+(e+f)(g+h)(a + b)(c + d) + (e + f)(g + h), one node per operation. Give its work, span and parallelism. Do the same for ((((a+b)+c)+d)+e)((((a + b) + c) + d) + e).

Solution

Solution of Exercise 24.2.

The four additions a+ba + b, c+dc + d, e+fe + f, g+hg + h have no inputs computed by other nodes; the two products each use two of them, and the final addition uses both products. Work 7, span 3 (an addition, a product, the final addition), parallelism 7/37/3. The second expression is a chain of four additions, each using the one before: work 4, span 4, parallelism 1. Since addition is associative, ((a+b)+(c+d))+e((a + b) + (c + d)) + e gives the same value with span 3.

Exercise 24.3 ★

A computation has work 10610^6 and span 10310^3. Bound the time of a greedy schedule on 8 processors, and on 10,000, from above and below. Beyond how many processors can the speed-up no longer grow much?

Solution

Solution of Exercise 24.3.

On 8 processors, max⁡(W/p,S)=max⁡(125,000,1,000)=125,000≤T8≤125,000+1,000=126,000\max(W/p, S) = \max(125{,}000, 1{,}000) = 125{,}000 \le T_8 \le 125{,}000 + 1{,}000 = 126{,}000. On 10,000 processors, max⁡(100,1,000)=1,000≤Tp≤100+1,000=1,100\max(100, 1{,}000) = 1{,}000 \le T_p \le 100 + 1{,}000 = 1{,}100. The parallelism is W/S=1,000W/S = 1{,}000: the speed-up can never exceed it, and beyond about a thousand processors the span dominates, so further processors add almost nothing.

Exercise 24.4 ★

exercises/ex4_loops.c holds three loops: y[i] = 2 * y[i + 1], y[i] = y[i - 4] + x[i] and y[i] = y[i - 1] + x[i]. Predict which of them gcc -O3 vectorises with 16-byte vectors of floats, then check with -fopt-info-vec-optimized.

Solution

Solution of Exercise 24.4.

(a) is vectorised: each iteration reads yi+1y_{i+1} before iteration i+1i + 1 overwrites it, and a vector of four iterations also reads yi+1,…,yi+4y_{i+1}, \ldots, y_{i+4} before writing yi,…,yi+3y_i, \ldots, y_{i+3}, so the order of reads and writes on each element is kept. (b) is vectorised: the four iterations of a 16-byte vector read yi−4,…,yi−1y_{i-4}, \ldots, y_{i-1}, all written by earlier vectors. (c) is not: iteration ii needs the value iteration i−1i - 1 has just written, so no two iterations can run at once. GCC reports lines 4 and 10 vectorised, with 16-byte vectors and 8-byte ones for the remainder, and line 16 missed; a test checks it.

Exercise 24.5 ★★

A parallel sum in C has each of its threads run total += a[i] on one global total. Run exercises/ex5_interleave.py, which plays the load, add and store of two threads in a scripted order, and explain the total it prints. Fix the C program so that it is correct for every interleaving without a lock in the loop.

Solution

Solution of Exercise 24.5.

Each += is three steps. In the script, thread 0 loads 0 and adds 5; thread 1 loads total, still 0, before thread 0 stores 5; thread 0 stores 5; thread 1 adds 3 to its register, 0, and stores 3 over the 5. The 5 is lost, and the remaining additions give 3+7+4=143 + 7 + 4 = 14 instead of 19. On real hardware the steps interleave at random, and the total varies from run to run. The fix, exercises/ex5_sum.c, gives each thread a local running sum over its own slice and stores it in its own slot of an array; the main thread adds the slots after joining all the threads, when no thread writes any more. Nothing is shared while the threads run, so no interleaving can lose an update. A C test compares the result with the sequential sum for 55 sizes and p=1p = 1 to 8.

Exercise 24.6 ★★

Write par_max(a: &[i64], p: usize) -> Option<i64>, which returns the largest element of a computed by pp scoped threads, and None if a is empty or p=0p = 0. Test it against the sequential maximum.

Solution

Solution of Exercise 24.6.

exercises/ex6_max.rs returns None for an empty slice or p=0p = 0. Otherwise it cuts the slice into chunks of ⌈n/p⌉\lceil n/p \rceil elements, spawns one scoped thread per chunk returning the chunk’s maximum (never empty, so unwrap is safe), and returns the maximum of the joined results. The scope guarantees that every thread has finished before the slice it borrows can be dropped. The Rust test compares it with a.iter().max() for 300 sizes and p=1p = 1 to 9, including pp larger than the slice.

Exercise 24.7 ★★

Prove that Hillis and Steele’s scan is correct, does nlog⁡2n−(n−1)n \log_2 n - (n - 1) additions for n=2kn = 2^k, and has span log⁡2n\log_2 n. For n=220n = 2^{20} and 8 processors, compare the two scans by Brent’s bound.

Solution

Solution of Exercise 24.7.

Facts used: induction on rounds. Claim: after the round of stride dd, position jj holds amax⁡(0,j−2d+1)+⋯+aja_{\max(0, j - 2d + 1)} + \cdots + a_j. Before the first round, with dd read as 1/21/2, it holds aja_j. A round of stride dd adds to xjx_j, for j≥dj \ge d, the old xj−dx_{j-d}, the sum of the dd values ending at j−dj - d; together they cover the 2d2d values ending at jj (or all values from a0a_0, clipped at the left). For j<dj < d, the old value already starts at a0a_0. After the round d=n/2d = n/2, every position holds a0+⋯+aja_0 + \cdots + a_j. The round of stride 2r2^r does n−2rn - 2^r additions, ∑r=0k−1(n−2r)=nk−(n−1)\sum_{r=0}^{k-1} (n - 2^r) = nk - (n - 1) in all, in kk rounds; each addition reads only results of the previous round, so the span is k=log⁡2nk = \log_2 n, as workspan.py measures. For n=220n = 2^{20} and p=8p = 8, Brent’s bound is 19,922,945/8+20≈2,490,38819{,}922{,}945/8 + 20 \approx 2{,}490{,}388 for Hillis and Steele and 2,097,150/8+40≈262,1842{,}097{,}150/8 + 40 \approx 262{,}184 for Blelloch: 9.5 times less. Even Hillis and Steele’s lower bound, W/p≈2,490,368W/p \approx 2{,}490{,}368, is above Blelloch’s upper bound: with 8 processors the extra work costs far more than the shorter span saves.

Exercise 24.8 ★★

Prove that the merge sort DAG of n=2kn = 2^k elements, with sequential merges as in workspan.py, has work nknk and span 2n−22n - 2. What is its parallelism, and why does the parallelism of psort.c stay small?

Solution

Solution of Exercise 24.8.

Facts used: the DAG’s recursive structure. Merge sort of nn elements is two sorts of n/2n/2 followed by a merge chain of nn nodes, and one element needs no node. The work satisfies W(n)=2W(n/2)+nW(n) = 2W(n/2) + n, W(1)=0W(1) = 0, so W(2k)=k2kW(2^k) = k 2^k: each of the kk levels of merges outputs nn elements. Both halves run in parallel and the merge chain needs both, so the span satisfies S(n)=S(n/2)+nS(n) = S(n/2) + n, S(1)=0S(1) = 0: S(2k)=2k+2k−1+⋯+2=2n−2S(2^k) = 2^k + 2^{k-1} + \cdots + 2 = 2n - 2. The parallelism nk/(2n−2)nk/(2n - 2) is a little above k/2=log⁡2(n)/2k/2 = \log_2(n)/2: 5.0 for 1,024 elements, and only 12 for 2242^{24}, far below nn. The last merge alone is a chain of nn steps, half the span; psort.c merges sequentially in the same way, so its parallelism is just as small, and the top merges keep most threads idle (exercise 24.12).

Exercise 24.9 ★★

Starting threads has a cost: model the time on pp processors as T(p)=f+(1−f)/p+cpT(p) = f + (1 - f)/p + cp, with T1=1T_1 = 1 apart from the cost. Find the real pp that minimises TT, and the best integer pp and speed-up for f=0.05f = 0.05 and c=0.001c = 0.001. What does the model say about adding processors beyond it?

Solution

Solution of Exercise 24.9.

T′(p)=−(1−f)/p2+cT'(p) = -(1 - f)/p^2 + c vanishes at p∗=(1−f)/cp^* = \sqrt{(1 - f)/c}, and T′′>0T'' > 0, so it is a minimum. For f=0.05f = 0.05, c=0.001c = 0.001: p∗=950≈30.8p^* = \sqrt{950} \approx 30.8; exercises/ex9_overhead.py finds the best integer, 31, with T=0.05+0.95/31+0.031≈0.112T = 0.05 + 0.95/31 + 0.031 \approx 0.112, a speed-up of 8.96, against Amdahl’s limit of 20 without the cost. Beyond p∗p^* the cost grows faster than the parallel part shrinks: adding processors makes the program slower, and the speed-up falls. With a cost ten times smaller, the best pp is 97 and the speed-up 14.39.

Exercise 24.10 ★★★

To merge two sorted arrays in parallel, take the median of the larger one, find by binary search where it falls in the other, and merge the two lower parts and the two upper parts in parallel. Prove that this merge has span O(log⁡2n)O(\log^2 n) and work O(n)O(n), and deduce the work and span of the merge sort that uses it.

Solution

Solution of Exercise 24.10.

Facts used: binary search takes O(log⁡n)O(\log n) steps; a recurrence S(n)≤S(3n/4)+clog⁡nS(n) \le S(3n/4) + c \log n solves to O(log⁡2n)O(\log^2 n). Let AA be the larger input, of m≥n/2m \ge n/2 elements, and BB the other. The median of AA splits it into two halves of at most m/2m/2 elements, and binary search splits BB at the same value; the elements of the lower parts are all at most those of the upper parts, so the two merges of the parts, placed side by side, give the merged output. Each part has at most m/2+∣B∣=n−m/2≤3n/4m/2 + |B| = n - m/2 \le 3n/4 elements. Span: the two recursive merges run in parallel, so S(n)≤S(3n/4)+clog⁡nS(n) \le S(3n/4) + c\log n; unrolling, the sizes shrink geometrically, there are O(log⁡n)O(\log n) levels, and each costs O(log⁡n)O(\log n): S(n)=O(log⁡2n)S(n) = O(\log^2 n). Work: W(n)=W(αn)+W((1−α)n)+clog⁡nW(n) = W(\alpha n) + W((1 - \alpha)n) + c\log n with 1/4≤α≤3/41/4 \le \alpha \le 3/4. Show W(n)≤an−blog⁡2nW(n) \le an - b\log_2 n by induction: the right-hand side is at most an−b(log⁡2(αn)+log⁡2((1−α)n))+clog⁡2n=an−2blog⁡2n−blog⁡2(α(1−α))+clog⁡2nan - b(\log_2(\alpha n) + \log_2((1 - \alpha)n)) + c\log_2 n = an - 2b\log_2 n - b\log_2(\alpha(1 - \alpha)) + c\log_2 n, and α(1−α)≥3/16\alpha(1 - \alpha) \ge 3/16, so it is at most an−blog⁡2nan - b\log_2 n as soon as (b−c)log⁡2n≥blog⁡2(16/3)(b - c)\log_2 n \ge b\log_2(16/3), which holds for b=2cb = 2c and n≥29n \ge 29; small nn are covered by choosing aa large. So W(n)=O(n)W(n) = O(n). Merge sort: W(n)=2W(n/2)+O(n)=O(nlog⁡n)W(n) = 2W(n/2) + O(n) = O(n\log n), the same work as sequentially, and S(n)=S(n/2)+O(log⁡2n)=O(log⁡3n)S(n) = S(n/2) + O(\log^2 n) = O(\log^3 n): the parallelism grows as n/log⁡2nn/\log^2 n, against log⁡n\log n with a sequential merge.

Exercise 24.11 ★★★

Prove that the blocked scan of Listing 24.9 is correct for any nn and pp. Count its additions, and its time on pp processors if each block costs its length and the middle scan is sequential. Show that its speed-up over the sequential scan, counted in additions, stays below p/2p/2, and say how to keep the middle step small for very large pp.

Solution

Solution of Exercise 24.11.

Facts used: induction on the blocks. Let the blocks be B0,…,Bq−1B_0, \ldots, B_{q-1}, q≤pq \le p (the last may be shorter, and an empty input gives no block). offset[i] is computed as offset[i-1] + sums[i-1], from offset[0] = 0, so by induction it is the sum of the blocks before BiB_i. Pass 2 starts each block’s running total from its offset, so the value written at a position of BiB_i is the sum of the blocks before BiB_i plus the values of BiB_i up to it: the inclusive prefix sum. Each block writes only its own part of out, which chunks_mut hands to its thread alone. Additions: pass 1 does nn (one per value), the middle q−1q - 1, pass 2 nn: 2n+q−12n + q - 1, against nn for the sequential scan. Time: with blocks of n/pn/p, Tp=n/p+(p−1)+n/p=2n/p+p−1T_p = n/p + (p - 1) + n/p = 2n/p + p - 1. The speed-up over the sequential scan, in additions, is n/(2n/p+p−1)<n/(2n/p)=p/2n/(2n/p + p - 1) < n/(2n/p) = p/2. For large pp the middle step dominates once p2p^2 approaches nn; it is itself a scan of pp values and can be done by Blelloch’s tree in O(log⁡p)O(\log p) rounds, giving Tp=2n/p+O(log⁡p)T_p = 2n/p + O(\log p).

Exercise 24.12 ★★★

Model psort.c: below the top log⁡2p\log_2 p levels each thread sorts n/pn/p elements alone, and at the top levels each merge is sequential. Derive TpT_p and the speed-ups the model predicts for p=2,4,8p = 2, 4, 8 and n=224n = 2^{24}, compare them with Output 24.2, and explain the shape of the gap.

Solution

Solution of Exercise 24.12.

At the top level one merge of nn elements runs alone; at the next, two merges of n/2n/2 run on two threads, and so on for log⁡2p\log_2 p levels: n+n/2+⋯+2n/p=2n(1−1/p)n + n/2 + \cdots + 2n/p = 2n(1 - 1/p) steps. Below, each of the pp threads sorts n/pn/p elements in (n/p)log⁡2(n/p)(n/p)\log_2(n/p) steps. So Tp=(n/p)log⁡2(n/p)+2n(1−1/p)T_p = (n/p)\log_2(n/p) + 2n(1 - 1/p) and T1=nlog⁡2nT_1 = n\log_2 n. For n=224n = 2^{24}: T1=24nT_1 = 24n, T2=12.5nT_2 = 12.5n, T4=7nT_4 = 7n, T8=4.375nT_8 = 4.375n, predicted speed-ups 1.92, 3.43 and 5.49. Output 24.2 measured 1.89, 3.24 and 4.47 on the author’s laptop: close for 2 threads, then further and further below. The model counts steps as if memory were free, but a merge does almost nothing but read and write memory: two inputs, an output, and a copy back. As more threads merge at once they share the path to memory, as the memory-bound sum of Output 24.1 did, so the gap grows with pp. The shape to expect is a curve under the model’s, bending away from it as pp grows.

24.7 Weekend problem

Problem 24.1

Weekend problem — Prefix sums of the town’s weather

The town’s two weather stations record the rain of every day. A running total answers questions such as how much rain fell between two dates: a subtraction of two totals. This problem computes the running totals of 2242^{24} days, the town’s two years repeated, sequentially and in parallel, and compares the parallel time with what the theory allows.

pub fn scan_par(a: &[i64], out: &mut [i64], p: usize) {
    let block = a.len().div_ceil(p).max(1);
    let sums: Vec<i64> = thread::scope(|s| {
        let hs: Vec<_> = a
            .chunks(block)
            .map(|c| s.spawn(move || c.iter().sum()))
            .collect();
        hs.into_iter().map(|h| h.join().unwrap()).collect()
    });
    let mut offset = vec![0; sums.len()];
    for i in 1..sums.len() {
        offset[i] = offset[i - 1] + sums[i - 1];
    }
    thread::scope(|s| {
        for ((c, o), off) in a.chunks(block).zip(out.chunks_mut(block)).zip(offset) {
            s.spawn(move || {
                let mut run = off;
                for (x, v) in o.iter_mut().zip(c) {
                    run += v;
                    *x = run;
                }
            });
        }
    });
}
Listing 24.9. The blocked scan: each block summed by its own thread, the block sums scanned in order, each block scanned again from its offset. code/bachelor-3/24-parallel-programming/listings/weather_scan.rs
$ rustc --edition 2021 -O -o weather_scan weather_scan.rs && ./weather_scan
sequential scan: 13.8 ms
 p  blocked scan ms  speed-up
 1             22.2      0.62
 2             14.0      0.99
 3             10.7      1.29
 4              8.7      1.59
 5              7.5      1.84
 6              7.0      1.96
 7              7.1      1.95
 8              7.2      1.91
Output 24.9. One run on the author’s laptop, best of five: the blocked scan against the sequential one, for 1 to 8 threads.
Speed-ups measured on the author’s laptop, from . The scan’s are against the sequential scan, which does half its additions.
Speed-ups measured on the author’s laptop, from Outputs 24.1 and 24.9. The scan’s are against the sequential scan, which does half its additions.

Part I — The sequential scan.

  1. How many additions does the sequential scan of nn values do, and what are its work and span as a DAG?
  2. Which dependency makes it sequential?
  3. How is the rain between day ii and day jj obtained from the totals, and in how many operations?
  4. Why can the totals be computed in another order at all? Which property of addition is used?
  5. Rain is stored in tenths of a millimetre, as integers. Why not as floats?
  6. What do the totals of the 8 days of Output 24.6 say about the first week?

Part II — Blelloch’s algorithm.

  1. What are the work and the number of rounds of Blelloch’s scan for n=224n = 2^{24}?
  2. Check in Output 24.6 that the work for n=220n = 2^{20} is 2(n−1)2(n - 1).
  3. Why is the span measured by workspan.py one less than the number of rounds?
  4. What is the parallelism of Blelloch’s scan for n=224n = 2^{24}?
  5. How many additions do Hillis and Steele need for n=224n = 2^{24}, and when would their scan be preferred?
  6. What does the blocked scan of Listing 24.9 do differently from Blelloch’s tree?

Part III — Brent’s bound.

  1. Write Brent’s bound for Blelloch’s scan of n=224n = 2^{24} on pp processors.
  2. What speed-up over the sequential scan does it guarantee on pp processors, counted in additions?
  3. Compute it for p=1,2,4,8p = 1, 2, 4, 8.
  4. What upper limit does the work law put on the same speed-up?
  5. Why do the two bounds almost coincide here?
  6. What would the bounds become on 1,000 processors?

Part IV — Measured.

  1. Why is the blocked scan on one thread slower than the sequential scan, but faster than half its speed?
  2. What speed-up does the laptop measure on 8 threads, against the bound of question 16?
  3. The compute-bound loop of Output 24.1 reaches more than 5. What makes the scan different?
  4. Why does the scan’s curve flatten at about the same number of threads as the memory-bound sum’s?
  5. What would make the parallel scan worth it on this machine?
  6. Sum up: what does the theory predict for 8 cores and n=224n = 2^{24}, and what does the laptop measure?
Solution

Solution of Problem 24.1.

1. The first total is a0a_0; each later one is one addition, n−1n - 1 in all (the program adds from 0, one more). As a DAG it is a chain: work n−1n - 1, span n−1n - 1, parallelism 1.

2. Each total is the previous total plus one value: every addition needs the result of the one before.

3. With inclusive totals Tj=a0+⋯+ajT_j = a_0 + \cdots + a_j, the rain from day ii to day jj is Tj−Ti−1T_j - T_{i-1} (or TjT_j if i=0i = 0): one subtraction, whatever the length of the period.

4. Associativity: a0+⋯+aia_0 + \cdots + a_i can be grouped in any way, so partial sums of blocks or of tree nodes can be computed first and combined later.

5. Integer addition is exact and associative. Floating-point addition rounds, so a parallel scan that groups the additions differently would give totals that differ in their last digits from the sequential ones, and the program’s check of equality would fail.

6. The exclusive totals end at 133 after the eighth day, and the eighth day had no rain: 13.3 mm fell in the first week, 6.2 mm of it on its second day.

7. Work 2(n−1)=33,554,4302(n - 1) = 33{,}554{,}430 additions, in 2×24=482 \times 24 = 48 rounds.

8. 2(220−1)=2,097,1502(2^{20} - 1) = 2{,}097{,}150, the value printed.

9. The last up-sweep addition computes the total at the root, which the down-sweep replaces by 0: no addition uses it, so the longest path of the DAG has 2k−12k - 1 nodes, one fewer than the rounds.

10. 33,554,430/47≈713,92433{,}554{,}430 / 47 \approx 713{,}924.

11. 24⋅224−(224−1)=385,875,96924 \cdot 2^{24} - (2^{24} - 1) = 385{,}875{,}969, eleven and a half times as many. Its span is half of Blelloch’s, which pays only when there are about as many processors as values, as on the lanes of a GPU for a short array.

12. It uses pp blocks instead of a tree of nn leaves: two passes over the data, each split among the threads, and a sequential scan of the pp block sums in between. Its work is about 2n2n, as Blelloch’s, but it has only three phases, and each thread reads consecutive memory.

13. Tp≤2(224−1)/p+47T_p \le 2(2^{24} - 1)/p + 47.

14. The sequential scan does about nn additions, so a guaranteed speed-up of n/(2(n−1)/p+47)n / (2(n - 1)/p + 47).

15. 0.50, 1.00, 2.00 and 4.00, to two decimals: the span changes nothing visible.

16. Tp≥W/p=2(n−1)/pT_p \ge W/p = 2(n - 1)/p, so the speed-up is at most np/(2(n−1))np/(2(n - 1)), about p/2p/2: 4 on 8 processors.

17. The parallelism, over 700,000, dwarfs 8: the span term 47 is negligible against W/pW/p, about 4 million, so the upper and lower bounds differ by about one part in 100,000.

18. On 1,000 processors, n/(2n/1,000+47)≈499.3n/(2n/1{,}000 + 47) \approx 499.3 guaranteed, against 500 at most: still almost equal, since 1,000 is far below the parallelism.

19. It reads the data twice, once to sum each block and once to scan it, where the sequential scan reads it once; but the first pass only reads, with no writes, and so costs less than a scan pass. The result, 0.62, lies between 0.5 and 1.

20. About 1.9 on 8 threads, against the bound of 4.

21. The scan does one addition for each 8-byte value it reads and each it writes: it is limited by memory, like the memory-bound sum. The compute-bound loop does 120 shift-and-xor steps, 240 operations, per value and touches no memory.

22. Both are bound by the same shared path to memory, which a few threads already saturate; beyond that, more threads only queue for it.

23. More computation per value read: a scan fused with the work that produces or consumes the values, while they are in cache, or a scan with an expensive operation. On data that fit in the cores’ caches, too, the threads would not compete for memory.

24. The theory guarantees almost exactly 4 on 8 cores for n=224n = 2^{24} (Brent’s bound and the work law agree to five digits), half of 8 because the parallel scan does twice the additions. The laptop measures about 1.9 in one run, under half the bound: on this machine the scan is limited by memory, not by additions, and the curve flattens after five or six threads.

Terms defined in this chapter

See all 1050 terms in the glossary