Volume 1 Exercises: Foundations of ComputingPractice for Volume 1
0 / 0

Workbench / Volume 1 Exercises: Foundations of Computing

V1·07

Computer Architecture

Exercises for Volume 1, chapter 07: gates and adders, the parts of a processor, the fetch–decode–execute cycle, clocks and the performance equation, memory, buses, interrupts and DMA, pipelining and hazards, branch prediction, superscalar, out-of-order and speculative execution, SIMD, caches (levels, lines, associativity, locality, coherence, false sharing), ISAs versus microarchitecture (x86-64, ARM64, RISC-V) and reading assembly. 12 theory questions, 11 programming exercises, 3 cumulative projects with chapters 01–06, the concepts the chapter leaves out, and 6 senior-level exercises.

39 exercises · ~15 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

Same four sets and the same locking. This chapter is where performance stops being abstract: most programming exercises are measurements, and you should predict the ratio (2×? 30×?) before you run them. All numbers in the solutions were measured on a 2-vCPU Intel Xeon cloud VM at 2.1 GHz (L1d 48 KB per core, L2 2 MB per core) with Java 21 and clang 18; your laptop will give different absolute numbers but the same shapes, and in one case (false sharing, P7) a different answer, which is itself the lesson.

For anything you time in Java, run each measurement several times and use the later runs: the first runs include JIT compilation (chapter 10). For real work use JMH.

Coverage map.

Chapter component Exercises
switches, gates, adders; ALU and flags T1, P1
registers, instruction pointer, stack pointer, control unit, fetch–decode–execute T2
clock, cycles, IPC; the performance equation T3
memory, words, DRAM; buses; interrupts; DMA; MMU and TLB (hardware side) T4
pipelining and hazards T5, P5
branch prediction; speculation T6, P4
superscalar, out-of-order execution, SIMD T7, P5, P9
cache levels and the memory hierarchy T8, P2
cache lines, associativity, replacement; locality T9, P2, P3, P6
cache coherence; false sharing; contention T10, P7, P8
ISA vs microarchitecture; x86-64, ARM64, RISC-V; reading assembly T11, T12, P9, P10
measuring hardware effects from software P11, S1

Theory

T1. From gates to an adder

  1. Show how NOT, AND, OR and XOR can each be built from NAND gates alone.
  2. Build a half adder and a full adder from those gates, and explain how 8 full adders make an 8-bit ripple-carry adder. Why is a ripple-carry adder slow for 64 bits, and what do real CPUs do instead (name the idea)?
  3. Using 8-bit addition, explain the difference between the carry flag and the overflow flag, with 200 + 100 and 100 + 100 as examples. Which one tells you a signed result is wrong?

T2. What the processor does each cycle

Explain, for the instruction add eax, [rbx+8] (add the 32-bit value at address rbx + 8 into register eax), what happens in each stage of fetch–decode–execute–memory–writeback, which registers are involved (including the instruction pointer), and what the stack pointer is for when the program calls a function. Then explain what a stack overflow is at this level.

T3. The performance equation

  1. CPU time = instructions × cycles per instruction (CPI) × seconds per cycle. A loop runs 3 × 10⁹ instructions at IPC 2.5 on a 3 GHz core: how long does it take? What if a change cuts instructions by 30% but drops IPC to 1.5?
  2. Why are GHz alone a poor guide to performance between different chips? Give two reasons.
  3. A RAM access costs about 100 ns (chapter's table). How many instructions could a 3 GHz core with IPC 3 have executed in that time, and what does that mean for code that misses cache on every iteration?

T4. Memory, buses, interrupts, DMA and the MMU

  1. Why is DRAM so much slower than the CPU, and why does it come in "channels"?
  2. When your Java program reads a file, explain what the disk controller, DMA, an interrupt and the CPU each do. Why don't we want the CPU copying each byte?
  3. What do the MMU, page tables and TLB do on every memory access? What does a TLB miss cost, and why do huge pages help some databases and JVMs?

T5. Pipelines and hazards

  1. Explain pipelining with a five-stage pipeline, and why it raises throughput without making any single instruction faster.
  2. Name and give an example of each hazard: data (read-after-write), control, structural. How does forwarding reduce data stalls?
  3. Why did the loop that summed doubles get 1.8× faster with four accumulators instead of one (P5), with the same number of additions?

T6. Branch prediction and speculation

  1. P4 summed the elements ≥ 128 of a million random bytes: unsorted took 125 ms (×20 passes) and sorted 15 ms in Java. Explain why, and estimate the misprediction cost per element.
  2. Name three ways to make such code fast regardless of data order.
  3. What is speculative execution, and how did Spectre turn it into a security problem? What did the mitigations cost?

T7. Doing more per cycle: superscalar, out-of-order, SIMD

  1. What do "4-wide superscalar" and "out-of-order with a reorder buffer" mean? Why must instructions still retire in order?
  2. What is SIMD? How many 32-bit ints does a 128-bit SSE register, a 256-bit AVX2 register and a 512-bit AVX-512 register hold? Give three everyday workloads that use SIMD.
  3. Why does adding cores not speed up a program automatically, while SIMD and out-of-order execution speed up single-threaded code?

T8. The memory hierarchy

Fill in typical sizes and latencies for registers, L1, L2, L3, DRAM, NVMe SSD and a same-region network round trip, then answer: (a) what's the ratio of a DRAM access to an L1 hit? (b) a hot loop's working set grows from 20 KB to 50 MB: what happens to its speed, and why does the curve have plateaus? (c) why does a modern CPU spend most of its area on cache?

T9. Cache lines, associativity and locality

  1. Caches move 64-byte lines. Explain spatial and temporal locality with an int[] loop and a HashMap lookup.
  2. Why did touching every 16th int of a 64 MB array take almost as long as touching every int (P3: 4.0 ms vs 4.9 ms)?
  3. What is set associativity? Explain how a power-of-two stride (accessing elements 4,096 bytes apart) can make a large cache behave like a tiny one.
  4. Why was column-order traversal of a int[4096][4096] 34× slower than row order in Java (P2), and why is Java's 2-D array layout different from C's?

T10. Coherence, false sharing and contention

  1. What does cache coherence guarantee, and what do the MESI states mean? What happens to a line that two cores both write?
  2. Explain false sharing and how Java avoids it (@Contended, padding, LongAdder).
  3. P8: two threads incrementing one AtomicLong took 2,230 ms for 100 million increments; the same work with LongAdder took 584 ms; one thread alone with incrementAndGet took 580 ms. Explain all three, and why a plain long[0]++ from two threads lost 475,786 increments.

T11. ISA versus microarchitecture

  1. Define ISA and microarchitecture, and give an example of one ISA with very different microarchitectures.
  2. Compare x86-64, ARM64 and RISC-V on: instruction length, number of general registers, memory-ordering model, licensing, and where you meet each.
  3. Why can the same Java .jar run on all three, while a Python package with a C extension or a Docker image may not? What does that mean for your build pipeline when your team gets ARM laptops or deploys to AWS Graviton?

T12. Reading assembly from your language

Using P9's output for int add3(int x, int y, int z) { return x + y * z; }:

Text
x86-64:  imull %edx, %esi ; leal (%rsi,%rdi), %eax ; retq
ARM64:   madd w0, w2, w1, w0 ; ret
RISC-V:  mul a1, a2, a1 ; addw a0, a0, a1 ; ret
  1. Where do the arguments arrive and where does the result go on each?
  2. Why does x86 use lea (load effective address) for an addition, and what is ARM's madd?
  3. Why is it worth being able to read this, as a Java developer? Name the tools that show the JIT's assembly.

Programming exercises

P1. Build an 8-bit adder from NAND

In Java, implement nand(a, b) on bits 0/1 and build NOT, AND, OR, XOR, a full adder and an 8-bit ripple-carry adder using only nand. Check it against (x + y) & 0xFF and (x + y) >> 8 for all 65,536 pairs. Print 200 + 100, 0xC8 + 56 and 100 + 100 with the carry, and 100 + 100 interpreted as a signed byte. Then add an overflow output and test it.

P2. Row order versus column order

Fill an int[4096][4096] (64 MB) and sum it in row order and in column order, three times each, printing the last run. Predict the ratio first. Then repeat with 512 × 512 (1 MB) and explain why the ratio shrinks.

P3. Lines, not elements

Allocate a 64 MB int[]. Time incrementing every element, then every 16th element, then every 32nd. Predict before you run. Then do the same with a 64 KB array repeated 1,000 times, and predict again.

P4. Branch prediction in Java

Fill an int[1 << 20] with random values 0–255, sort a copy, and time for (int x : d) if (x >= 128) s += x; 20 times over each, repeating the measurement 10 times and printing the last. Then write a branchless version and time it on unsorted data. Finally, check whether the JIT used a branch with -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly if you have hsdis, or JMH's perfasm.

P5. Breaking dependency chains

Sum a double[1 << 22] ten times with one accumulator, then with four (s0..s3, unrolled by 4). Print both. Repeat with long values and explain why the difference disappears for integers.

P6. Matrix multiply and loop order

Multiply two 512 × 512 double matrices with the textbook i-j-k loop order and with i-k-j order (hoisting A[i][k] and rows B[k], C[i]). Print both times and check whether the results are equal. Explain the difference in terms of which arrays are accessed sequentially.

P7. Look for false sharing (and learn why the VM hid it)

Using AtomicLongArray (so the JIT can't keep the counters in registers), run two threads that each update their own element 50 million times with setOpaque(i, getOpaque(i) + 1), first with the elements adjacent (indices 8 and 9, same cache line) and then 16 longs apart (128 bytes). Repeat with incrementAndGet. Run it on this kind of cloud VM and on your own multicore laptop. Explain what you see on each.

P8. Contention: AtomicLong, LongAdder and a race

Measure: one thread doing 100 million incrementAndGet on an AtomicLong; two threads doing 50 million each on the same AtomicLong; the same with a LongAdder; and two threads doing plain[0]++ on a shared long[1] (print the final value). Explain each result.

P9. One function, three ISAs

Compile int sum(const int *a, int n) (a simple loop) and int add3(int x, int y, int z) for x86-64, ARM64 and RISC-V with clang --target=<triple> -O2 -S -o - f.c (triples x86_64-linux-gnu, aarch64-linux-gnu, riscv64-linux-gnu), and at -O0. Count the instructions in sum for each and find the SIMD instructions in the x86 output. Explain why -O2 has more instructions than -O0 on x86 and ARM but fewer on RISC-V.

P10. Instruction encodings

Compile add3 with gcc and disassemble with objdump -d. Print the bytes of each instruction. Then do the same for ARM64 (clang --target=aarch64-linux-gnu -O2 -c and llvm-objdump -d if available). What does this tell you about decoding?

P11. Measure your own machine's hierarchy

Write a Java (or C) pointer-chasing benchmark: build a random cyclic permutation in an int[] of size N (so next = a[next] visits every element in random order), walk it 10 million steps, and print nanoseconds per step for N from 4 K to 64 M elements (doubling). Plot or print the curve and identify your L1, L2, L3 and DRAM plateaus. Compare against lscpu (or System Information on Windows/macOS).

Cumulative projects (chapters so far: 01–07)

C1. Make the TiffinBox order lookup fast

The order service keeps 5 million active orders in memory as HashMap<Long, Order> (each Order an object with an ID, kitchen ID, amount in paise, status enum and timestamp). A report scans all orders every minute to total amounts per kitchen. Design and measure a structure-of-arrays alternative: parallel primitive arrays (long[] ids, int[] kitchen, long[] amount, byte[] status, long[] ts) plus an open-addressing index from ID to slot. Measure memory (via a heap histogram or Runtime before/after) and the time of the per-kitchen scan for both, and explain the difference with cache lines. Discuss what you lose.

Combines: CLI measurement tools (ch 01); objects, records, enums (ch 02); hash tables, arrays and memory overhead (ch 03); linear scans and complexity (ch 04); estimating memory by counting (ch 05); primitive sizes and money as minor units (ch 06); cache lines, prefetching, locality (ch 07).

C2. A cache-aware sort benchmark

Implement merge sort on int[] in Java three ways: top-down recursive (allocating temporaries), bottom-up with one preallocated buffer, and bottom-up with insertion sort for runs of 32. Compare them with Arrays.sort (dual-pivot quicksort) and Arrays.parallelSort on 10 million random ints, sorted input and reverse input. Explain each result in terms of comparisons (chapter 04), memory traffic, branch prediction and cores (this chapter), and produce a short report table generated by a script.

Combines: shell scripting and output (ch 01); clean Java code and tests (ch 02); arrays (ch 03); sorting and complexity (ch 04); counting comparisons (ch 05); integer types (ch 06); caches, branches, cores (ch 07).

C3. A latency budget for one API request

TiffinBox's GET /orders/{id} must respond in under 50 ms at the 99th percentile. Its path: TLS-terminated request arrives, JSON parse, a lookup in an in-process cache (C1), on a miss a database query over the network (~1 ms round trip + query), JSON serialisation, response. Build a latency budget table using this chapter's numbers (and chapter 05's percentile reasoning): which steps are nanoseconds, microseconds, milliseconds? Then write a small Java harness that simulates the path with realistic costs (in-memory lookup, Thread.sleep-free busy work for parsing, a simulated 1–3 ms DB call with a heavy tail) and measures p50, p99 and p99.9 with and without a 95%-hit cache.

Combines: measurement and output (ch 01); exceptions and timeouts (ch 02); hash maps (ch 03); percentiles and sorting (ch 04); probability and tails (ch 05); time units and number types (ch 06); the memory hierarchy and orders of magnitude (ch 07).

What the chapter leaves out

Memory models: what other cores are allowed to see

Coherence (T10) is about one location. A memory model says in what order writes to different locations become visible to other cores. x86 is strong (TSO: a core's stores are seen in order, but a later load may pass an earlier store); ARM64 and RISC-V are weak (loads and stores can be reordered unless you use barriers or acquire/release instructions). Languages define their own models on top: the Java Memory Model promises sequentially consistent behaviour only for data-race-free programs, and volatile, synchronized, final fields and java.util.concurrent classes insert the right barriers on each ISA. Code that "works" with a data race on x86 can fail on Graviton or an Apple laptop: the classic is double-checked locking without volatile. Volume 3's concurrency chapter goes deeper; the architectural reason is here.

Performance counters and profiling the hardware

CPUs count events: cycles, instructions (so IPC), cache misses per level, branch mispredictions, TLB misses. perf stat and perf record on Linux, Intel VTune, AMD uProf, Apple Instruments, and for Java async-profiler (CPU, allocation, lock and hardware-event profiling with flame graphs) and JMH's perfnorm/perfasm read them. Intel's top-down method classifies stalls as front-end bound, bad speculation, back-end (memory/core) bound or retiring, which tells you which of this chapter's effects is your bottleneck before you guess. Cloud VMs often hide these counters (this book's sandbox does), another reason to profile on representative bare-metal or properly configured instances.

Frequency, turbo, thermals and noisy measurements

Clock speed isn't fixed: turbo raises it when few cores are busy and thermal headroom exists, and throttling lowers it when hot or on battery; heavy AVX-512 code lowered clocks on some Intel generations. A laptop benchmark that runs 20% faster for the first 10 seconds is measuring turbo. In the cloud, a vCPU is often a hyperthread (P7), neighbouring tenants share caches and memory bandwidth, and "steal time" appears when the hypervisor runs someone else. Pin frequencies where you can, run long enough, repeat, report variance, and compare like with like.

NUMA

Servers with several sockets (and some large single-socket chips) have non-uniform memory access: each socket has its own memory, and reaching the other socket's memory costs maybe 1.5–2× the latency. The OS and JVM try to allocate memory near the thread using it (-XX:+UseNUMA with Parallel and G1 collectors), and databases pin threads to sockets. On a 2-socket database server, an unlucky thread placement can cost 20–30% throughput. Check lscpu or numactl --hardware on production machines.

GPUs and accelerators

A GPU is thousands of simple cores running the same instructions on different data (SIMT: SIMD across threads), with very high memory bandwidth and deep latency-hiding by switching between thousands of threads instead of caching and speculating. It wins for data-parallel work (graphics, matrix multiplies, ML training and inference) and loses for branchy, serial, latency-sensitive code. Moving data over PCIe to and from the GPU is often the bottleneck. TPUs, NPUs in phones and laptops, video encoders and crypto engines are further specialised units. Volume 14's AI chapters assume this picture.

Energy and efficiency cores

Modern chips mix performance and efficiency cores (Apple, Intel since 12th generation, ARM big.LITTLE). The OS decides where threads run, so the same code can run at very different speeds; background work belongs on efficiency cores, latency-sensitive threads on performance cores (QoS classes on macOS, thread priorities elsewhere). Energy per operation is now a design constraint: moving data from DRAM costs far more energy than computing on it, which is another argument for locality, and in the data centre, power and cooling, not CPU count, often limit capacity.

Senior exercises

S1. Diagnose a slow service with the hardware in mind

A Java service's CPU usage is at 70% but throughput hasn't improved after doubling its instance size from 8 to 16 vCPUs. A flame graph shows time spread across HashMap.get, ConcurrentHashMap.addCount and a metrics library's Counter.increment. Using this chapter, list the hypotheses, the measurements that would confirm or reject each (with tools), and the likely fixes.

S2. Review a "performance improvement" PR

A colleague's PR replaces List<Order> processing with hand-unrolled loops, replaces if statements with bit tricks "to avoid branch mispredictions", and adds @Contended-style padding to a configuration object read by all threads. The PR description says "15% faster in my benchmark" (a main method timing one run with System.currentTimeMillis). Write the review.

S3. Plan a move from x86 to ARM servers

Your team wants to move its Java services from x86 instances to AWS Graviton (ARM64) for cost. Write the plan: what to inventory, what can break (native libraries, base images, memory-model bugs, performance differences), how to test, and how to roll out and measure the benefit.

S4. Choose the data layout for a hot in-memory index

You're building an in-memory index of 200 million (kitchen ID, dish ID, price) tuples for a recommendation service, queried with "all dishes of kitchen K under price P". Compare: HashMap<Integer, List<Dish>>, a sorted primitive array with binary search, and a columnar SoA layout grouped by kitchen with offset arrays. Estimate memory and query cost with this chapter's numbers, choose one, and explain what you'd measure to confirm.

S5. Explain Spectre-era decisions to a product manager

Your browser-facing product needs high-resolution timing for a feature (precise animation scheduling), but performance.now() is coarsened and SharedArrayBuffer needs cross-origin isolation headers. Explain to a product manager, in plain language and under 250 words, why browsers did this, what the team needs to do (COOP/COEP headers) and the trade-offs, with this chapter's concepts underneath.

S6. Teach the memory hierarchy with one analogy and one number

Write a one-page explainer for junior engineers that uses a single analogy for the memory hierarchy (scaling 1 ns to a human time unit), shows what a cache miss, an SSD read and a network round trip feel like at that scale, and ends with three rules they can apply in code review. Then say how you'd check that it worked.