Course contents 01 / 32

01 / 32 · Foundations

What a computer system is

What happens between typing a program and seeing its output: the layers of hardware and software involved, the stored-program idea and the fetch–decode–execute cycle, how processors got fast and why that stopped, and the equation that predicts running time.

On this page 9

A program is a text file. When we run it, characters appear on a screen a few milliseconds later, and between the two stand a compiler, a linker, an operating system, a processor executing billions of instructions per second, memory chips, a display driver and transistors switching on and off. Each of them is a layer built so that the layer above does not have to think about it. This course opens those layers one at a time, from the bits of a single number to a process talking to another over the network. This first note draws the whole picture: what happens when a program runs, the idea that makes a general-purpose computer possible, how processors became fast and why they stopped getting faster in the old way, and how to reason about running time with one equation.

Notation. For the performance equation, II is the number of instructions a program executes (its dynamic instruction count), CPI\mathrm{CPI} the average number of clock cycles per instruction, TcT_c the clock period and f=1/Tcf = 1/T_c the clock rate. Numbers written 0x… are hexadecimal; the next note explains them.

What happens when a program runs#

Take the smallest C program that does something visible:

#include <stdio.h>
int main(void) { printf("hello, world\n"); return 0; }
Figure

The path of hello.c from source text to pixels

Six steps from hello.c to the screenSix boxes joined by arrows: hello.c, compiler and linker, loader, processor, kernel, terminal. The arrows are labelled cc hello.c, ./hello, start, ecall and 13 bytes.buildingrunningcc hello.c./hellostartecall13 byteshello.csource: bytes on disk1compiler, linkerC → machine code2loaderfile → process memory3processorfetch, decode, execute4kernelwrite(1, buf, 13)5terminalbytes → pixels6Six steps from hello.c to the screenSix boxes joined by arrows: hello.c, compiler and linker, loader, processor, kernel, terminal. The arrows are labelled cc hello.c, ./hello, start, ecall and 13 bytes.cc hello.c./hellostartecall13 byteshello.csource: bytes on disk1compiler, linkerC → machine code2loaderfile → process memory3processorfetch, decode, execute4kernelwrite(1, buf, 13)5terminalbytes → pixels6
The six steps, numbered as in the list under the figure. Top row, building: the source file (1) becomes an executable (2). Bottom row, running: the kernel loads the file into a new process's memory (3), the processor executes its instructions (4), the call write with the 13 bytes of "hello, world\n" enters the kernel through a system call (5), and the terminal draws the characters (6). Each box is the subject of one or more sections of the course.
  1. Source. hello.c is a file of bytes on disk, one byte per character in ASCII. The string "hello, world\n" alone is 13 bytes: twelve printable characters, the space among them, and the newline.
  2. Build. The compiler driver runs four programs in turn. The preprocessor pastes in the text of stdio.h; the compiler translates C into assembly language for the target processor; the assembler turns assembly into machine code, a sequence of numbers, in an object file; the linker joins it with the code of printf from the C library into an executable file.
  3. Load. We type ./hello into a shell. The shell asks the operating system to create a new process and run the file in it. The kernel’s loader maps the executable into the process’s memory and starts it at its entry point.
  4. Execute. The processor fetches the instructions of main from memory one after another and executes them. printf formats the string into a buffer and calls write(1, buffer, 13): write 13 bytes to file descriptor 1, the standard output.
  5. System call. write cannot touch the terminal itself. It executes a special instruction that switches the processor into the kernel, which checks the request and hands the 13 bytes to the terminal’s driver.
  6. Output. The terminal program turns the bytes into glyphs, the graphics hardware turns glyphs into pixels, and the display shows hello, world.

The program contains one function call. Running it involves every section of this course: the representation of characters as bytes, the instruction set the compiler targets, the memory the program lives in, the processor executing it, the system call that crosses into the kernel, the process that hosts it, the file descriptor it writes to, and the compiler and linker that built it.

Layers of abstraction#

A computer is understandable because it is built in layers. Each layer offers an interface to the layer above and hides how it is implemented. A C programmer sees variables and functions, not registers; a compiler sees instructions, not the pipeline that executes them; an instruction set says what add does, not how many transistors do it.

LayerWhat it offers aboveWhat it hidesWhere in this course
Application and algorithma solution to a problemhow it is computedexamples throughout
Programming language and runtimevariables, functions, objectsregisters, addressesLanguages and Compilers
Compiler, assembler, linkertranslation into machine codeinstruction choice, register allocationLanguages and Compilers; linking in The Operating System
Operating systemprocesses, files, socketsdevices, physical memory, other programsThe Operating System to Networking
Instruction set architecture (ISA)instructions, registers, memory addressesthe hardware that executes themRISC-V Assembly
Microarchitecturean implementation of the ISApipelines, caches, parallel unitsMemory Hierarchy to Parallelism and Performance
Logic and circuitsgates, adders, registerstransistorsmentioned where needed
Devicestransistors that switchphysicsthe history below

The most important line is the instruction set architecture. It is the contract between hardware and software: any program written for RISC-V runs on any processor that implements RISC-V, from a microcontroller to a server, although they share no circuits. The processor and ISA note starts there.

Abstraction does not make the lower layers irrelevant. The layers leak. On an Apple M1, a C program that multiplies two 1024×10241024 \times 1024 matrices with the textbook triple loop, compiled with clang -O0, took 5.4 seconds in one run; the same program with two loops swapped took 1.5 seconds and computes the same result: every element is summed over kk in the same order (the Code section). Nothing in C distinguishes the two orders. The difference lives in the memory hierarchy, two layers down, and the caches note explains it. Writing fast and correct programs requires knowing what each layer hides.

Baseline: a machine wired for one problem#

The first electronic computers were built for one kind of calculation at a time. ENIAC, completed at the University of Pennsylvania in 1945 for artillery tables, had about 18,000 vacuum tubes, drew 150 kW and did about 5,000 additions per second. Its program was not stored anywhere: it was the wiring. Operators connected units with cables on plugboards and set thousands of switches, and changing the problem took days of rewiring before testing could begin (ENIAC, Wikipedia).

This works as long as the problem does not change. It breaks as soon as a machine has to serve many users and many problems: the computer is idle while it is rewired, every program change is a hardware change, and a program cannot do the one thing that makes software powerful, which is to produce or modify another program.

The stored-program computer#

The idea is set out in John von Neumann’s First Draft of a Report on the EDVAC, dated 30 June 1945, written with the ENIAC team (von Neumann, 1945). It describes a machine with a central arithmetic part, a central control part, a memory, and input and output, in which instructions are coded as numbers and held in the memory. The first machine to run a program stored in its own electronic memory was the Manchester Baby, on 21 June 1948: 17 instructions in a memory of 32 words of 32 bits each (Manchester Baby, Wikipedia). The organization is still called the von Neumann architecture:

  • a memory, an array of numbered cells holding both instructions and data;
  • a processor with a small set of registers, an arithmetic logic unit (ALU) that computes, and a control unit that decides what happens next;
  • a program counter (PC), the register that holds the address of the next instruction;
  • input and output devices connected to the same system.

A machine with separate memories for instructions and data is called a Harvard architecture. Modern processors are a mix: one memory and one address space, as in von Neumann’s design, but separate fast caches for instructions and data close to the processor.

The fetch–decode–execute cycle#

The control unit runs one loop, forever:

Figure

One trip around the fetch–decode–execute loop

Fetching, decoding and executing an add instructionOn the left, PC holds 0x00400008 and points at the third row of memory, which holds the word 0x00B50633. An arrow leads from memory to the processor's instruction register IR, then to a decoder showing add, a2, a0 and a1. Registers a0 = 5 and a1 = 7 feed the ALU adder, whose result 12 goes back into a2. Below, PC becomes 0x0040000C.memoryaddressword0x004000000x005005130x004000040x007005930x004000080x00B50633PC0x00400008IR0x00B506331processoradd · rd = a2 · rs1 = a0 · rs2 = a12registersa05a17a212+ALU3124PC ← PC + 4 = 0x0040000C5Fetching, decoding and executing an add instructionOn the left, PC holds 0x00400008 and points at the third row of memory, which holds the word 0x00B50633. An arrow leads from memory to the processor's instruction register IR, then to a decoder showing add, a2, a0 and a1. Registers a0 = 5 and a1 = 7 feed the ALU adder, whose result 12 goes back into a2. Below, PC becomes 0x0040000C.memoryaddressword0x004000000x005005130x004000040x007005930x004000080x00B50633PC0x00400008IR0x00B506331processoradd · rd = a2 · rs1 = a0 · rs2 = a12registersa05a17a212+ALU3124PC ← PC + 4 = 0x0040000C5
The third instruction of the three-instruction program loaded at 0x00400000. PC points at 0x00400008 (1), and the word 0x00B50633 is copied into the instruction register IR. The decoder extracts its fields (2): the operation add, the destination a2 and the sources a0 and a1, which the two previous instructions set to 5 and 7. The ALU adds them (3), the result 12 is written into a2 (4), and PC advances by 4 (5). The memory holds only numbers; a word is an instruction because PC points at it.
  1. Fetch. Read the instruction at the address in PC from memory into the instruction register (IR).
  2. Decode. Split the instruction into fields: which operation, which registers to read, which register to write, and any constant.
  3. Execute. Read the source registers and let the ALU compute the result (or compute a memory address, or compare for a branch).
  4. Write back. Write the result into the destination register (or into memory).
  5. Next. Advance PC to the next instruction, 4 bytes further for 32-bit instructions, unless the instruction was a jump or a taken branch, which sets PC instead.

Worked example. A three-instruction RISC-V program, loaded at the address 0x00400000 where the RARS simulator places code:

AddressMachine wordAssemblyEffect
0x004000000x00500513addi a0, zero, 5a0 ← 0 + 5
0x004000040x00700593addi a1, zero, 7a1 ← 0 + 7
0x004000080x00B50633add a2, a0, a1a2 ← a0 + a1

The figure shows the third trip around the loop. PC holds 0x00400008; the fetch copies the word 0x00B50633 into IR. The decoder reads its fields: operation add, destination register 12 (a2), sources 10 (a0) and 11 (a1). The ALU receives 5 and 7 and produces 12, which is written into a2, and PC becomes 0x0040000C. The memory holds only numbers; whether 0x00B50633 is an instruction or an integer depends on whether PC points at it. How the fields are packed into the 32 bits is the subject of the instruction-encoding note.

Every processor in this course, however elaborate, implements this loop. A pipelined processor works on several instructions at once, each in a different stage of the loop; a superscalar processor fetches several per cycle; an out-of-order processor executes them in a different order. All of them must produce the same result as executing the instructions one at a time in program order, because that is what the ISA promises.

How processors got fast, and why that changed#

The stored-program idea fixed the organization. What changed over the following decades was the technology underneath, and with it the speed and the cost.

  • Vacuum tubes (1940s–1950s). ENIAC, EDSAC, UNIVAC: room-sized, power-hungry, and unreliable, because tubes burned out often.
  • Transistors (from the late 1950s). The transistor was invented at Bell Labs in 1947. A transistor switches like a tube but is smaller, faster, cooler and lasts far longer. Mainframes such as the IBM 7090 were built from discrete transistors.
  • Integrated circuits (from the 1960s). Jack Kilby (1958) and Robert Noyce (1959) put several transistors and their wiring on one piece of silicon. In 1971 the Intel 4004 placed a whole processor on one chip with about 2,300 transistors.
  • Moore’s law. In 1965 Gordon Moore observed that the number of components on a chip of minimum cost doubled every year and predicted that it would continue (Moore, 1965); in 1975 he revised the rate to a doubling about every two years. The revised rate held for decades: an Apple M1 of 2020 has about 16 billion transistors, some seven million times as many as the 4004.

More transistors alone would not have made processors faster. What made them faster for free was a second rule.

Dennard scaling. Dennard et al. (1974) showed how to shrink a transistor so that it gets better in every respect. Scale every length and the supply voltage by 1/κ1/\kappa, for some κ>1\kappa > 1. Then:

C∝1/κcapacitance shrinks with the dimensionsf∝κa smaller, lower-voltage transistor switches fasterPtransistor∝CV2f=1κ⋅1κ2⋅κ=1κ2dynamic powertransistors per area∝κ2power per area∝κ2⋅1κ2=1.\begin{aligned} C &\propto 1/\kappa && \text{capacitance shrinks with the dimensions} \\ f &\propto \kappa && \text{a smaller, lower-voltage transistor switches faster} \\ P_{\text{transistor}} &\propto C V^2 f = \tfrac1\kappa \cdot \tfrac1{\kappa^2} \cdot \kappa = \tfrac{1}{\kappa^2} && \text{dynamic power} \\ \text{transistors per area} &\propto \kappa^2 \\ \text{power per area} &\propto \kappa^2 \cdot \tfrac1{\kappa^2} = 1 . && \end{aligned}

Each generation, with κ≈2\kappa \approx \sqrt 2 so that the transistor count per area doubles, gave twice as many transistors, each about 1.4 times faster, at the same power per square millimetre. Architects spent the transistors on deeper pipelines, larger caches and more instructions per cycle, and single-processor performance grew by about 52 % per year from 1986 to 2003 (Hennessy and Patterson, 2019, §1.1).

The end of Dennard scaling. The supply voltage cannot keep falling. A transistor’s threshold voltage has to fall with it, and below a few hundred millivolts the current that leaks through a transistor that is “off” grows rapidly. Once VV stays fixed, the same shrink gives Ptransistor∝1κ⋅1⋅κ=1P_{\text{transistor}} \propto \frac1\kappa \cdot 1 \cdot \kappa = 1, and power per area grows by κ2\kappa^2, doubling each generation if the clock keeps rising. A chip can only dissipate about 100 W or so before cooling becomes impractical. Around 2005 the industry hit this power wall: clock rates of desktop processors stopped near 3–4 GHz (Patterson and Hennessy, 2020, §1.7), and single-processor performance growth fell to about 23 % per year until 2011 and about 3.5 % per year after 2015 (Hennessy and Patterson, 2019, §1.1).

Multicore and accelerators. Moore’s law kept supplying transistors, so they went into more processors per chip instead of faster ones: dual-core desktop processors appeared in 2005, and today’s chips have from a few to over a hundred cores. A second answer is specialization: graphics processors and machine-learning accelerators such as Google’s TPU do one class of computation with far more operations per watt than a general-purpose core (Jouppi et al., 2017). Neither speeds up an existing sequential program by itself. The program has to be rewritten to use parallelism, which is why the course spends a whole section on it.

How long does a program take?#

Running time is the only measure of performance that cannot mislead. It decomposes into three factors, the performance equation (Patterson and Hennessy, 2020, §1.6):

  time=I×CPI×Tc=I×CPIf  \boxed{\;\text{time} = I \times \mathrm{CPI} \times T_c = \frac{I \times \mathrm{CPI}}{f}\;} secondsprogram=instructionsprogram×cyclesinstruction×secondscyclethe units cancel in pairsI: set by the algorithm, the language, the compiler and the ISACPI: set by the microarchitecture and the memory system, and by the instruction mixTc: set by the circuit technology and the microarchitecture.\begin{aligned} \frac{\text{seconds}}{\text{program}} &= \frac{\text{instructions}}{\text{program}} \times \frac{\text{cycles}}{\text{instruction}} \times \frac{\text{seconds}}{\text{cycle}} && \text{the units cancel in pairs} \\ I &\text{: set by the algorithm, the language, the compiler and the ISA} \\ \mathrm{CPI} &\text{: set by the microarchitecture and the memory system, and by the instruction mix} \\ T_c &\text{: set by the circuit technology and the microarchitecture.} \end{aligned}

When instructions fall into classes with different costs, the average CPI is the average of the class CPIs weighted by how often each class runs: if class jj makes up a fraction pjp_j of the executed instructions and takes CPIj\mathrm{CPI}_j cycles, then CPI=∑jpj CPIj\mathrm{CPI} = \sum_j p_j\, \mathrm{CPI}_j.

Worked example. A program executes I=2×109I = 2 \times 10^9 instructions on a processor with f=3f = 3 GHz, so Tc=1/(3×109 Hz)=0.333T_c = 1/(3 \times 10^9\ \text{Hz}) = 0.333 ns. Half of its instructions are arithmetic (CPI 1), 30 % are loads and stores (CPI 2 on average, counting the occasional slow memory access) and 20 % are branches (CPI 1.5):

CPI=0.5⋅1+0.3⋅2+0.2⋅1.5=1.4,time=2×109⋅1.43×109 Hz=0.933 s.\begin{aligned} \mathrm{CPI} &= 0.5 \cdot 1 + 0.3 \cdot 2 + 0.2 \cdot 1.5 = 1.4, \\ \text{time} &= \frac{2 \times 10^9 \cdot 1.4}{3 \times 10^9\ \text{Hz}} = 0.933\ \text{s}. \end{aligned}

A better compiler removes 0.2×1090.2 \times 10^9 arithmetic instructions. The new mix has 0.80.8, 0.60.6 and 0.40.4 billion instructions in the three classes, so the program needs 0.8⋅1+0.6⋅2+0.4⋅1.5=2.60.8 \cdot 1 + 0.6 \cdot 2 + 0.4 \cdot 1.5 = 2.6 billion cycles: 0.867 s, 7 % faster. Yet the average CPI rose, from 1.4 to 2.6/1.8=1.4442.6/1.8 = 1.444, because the cheap instructions were the ones removed. No single factor of the equation measures performance; only the product does. The same goes for clock rate alone (a 4 GHz design whose CPI is 40 % higher is slower than the 3 GHz one: 1.4⋅1.4/4>1.4/31.4 \cdot 1.4/4 > 1.4/3) and for “millions of instructions per second”, which rewards executing many cheap instructions.

Worked example (measured). The matrix multiplication of the previous section, with n=1024n = 1024: the innermost statement C[i][j] += A[i][k] * B[k][j] runs n3=230≈1.07×109n^3 = 2^{30} \approx 1.07 \times 10^9 times in every loop order. Compiled with clang -O0 for the M1’s ARM instruction set, each trip through the inner loop is 29 instructions in the assembly that clang -O0 -S prints, the same for every loop order (only which index sits in which loop changes), so I≈29⋅230≈3.1×1010I \approx 29 \cdot 2^{30} \approx 3.1 \times 10^{10} in all three versions, and TcT_c is the same. Therefore the ratio of the running times is the ratio of the CPIs. In one run, the orders i, j, k, i, k, j and j, k, i took 5.4 s, 1.5 s and 6.4 s: the slowest order spends about 4.3 times as many cycles per instruction as the fastest. If the core ran at its maximum of about 3.2 GHz, the CPIs were about 0.55, 0.15 and 0.66; a CPI below 1 means the processor completes several instructions per cycle, a topic of the instruction-level parallelism note. The algorithm and the instruction count are identical; the memory access pattern is not.

The plan of the course#

The course follows the hello-world program down through the layers and back up, in ten sections.

  1. Foundations. This note, then how integers and real numbers are represented in bits: two’s complement, byte order, IEEE 754 floating point.
  2. RISC-V Assembly. The instruction set as the contract between hardware and software: registers, instruction encodings, branches, loops and memory access, and procedures and the stack, written and run in RARS.
  3. Memory Hierarchy. Why a memory that is large, fast and cheap at once is impossible, and how caches and virtual memory make it look as if it existed, with every program in a private address space.
  4. Inside the Processor. The datapath and its pipeline, which carry out the fetch–decode–execute loop for several instructions at once, exceptions and interrupts, which break the loop, and input and output.
  5. Parallelism and Performance. Doing more per cycle, per core and per instruction: instruction-level, thread-level and data-level parallelism, making programs fast, and domain-specific architectures such as the TPU.
  6. The Operating System. What the kernel does, C for systems programming, system calls such as the write of the hello-world program, linking and loading, and dynamic memory allocation.
  7. Processes and Concurrency. Processes and threads, the synchronization that keeps concurrent code correct, and inter-process communication.
  8. Files, Users and Isolation. Files and file descriptors, users and permissions, and virtual machines and containers.
  9. Networking. How bytes travel between machines in computer networks, and the sockets a program uses to send them.
  10. Languages and Compilers. What language runtimes ask of the operating system, and how a compiler turns source code into the instructions this course started from.

What changed#

Fixed-program machine (ENIAC, 1945)Stored-program computer
Where the program livesin cables and switch settingsin memory, as numbers
Changing the programdays of rewiringwriting new numbers into memory
Programs that make programsimpossiblecompilers, linkers, loaders
What the hardware doesone configured calculationone fixed loop: fetch, decode, execute, next
Speed-up pathfaster circuitsfaster circuits, then more instructions per cycle, then more cores

Limitations#

  • The von Neumann bottleneck. Every instruction and every operand passes between processor and memory over one connection, and memory became far slower than processors. Backus (1978) named this bottleneck; caches, the subject of the caches note, are the main answer.
  • The performance equation is exact but not predictive by itself. CPI is not a property of a processor: it depends on the program, its data and the memory system, so it has to be measured. The equation also ignores time spent waiting for input and output or for other programs.
  • Layers leak. Performance, security bugs and some failures can only be understood a layer or two below the one the program is written in.
  • The history is simplified. Many machines and people contributed to each step; this note names only a few milestones.

What you should remember#

  • A program runs through a chain of layers: compiler, assembler and linker build it; the operating system loads it; the processor executes it; system calls reach devices through the kernel.
  • The instruction set architecture is the contract between hardware and software.
  • The stored-program idea: instructions are numbers in memory, and the processor repeats fetch, decode, execute, write back, advance PC.
  • Dennard scaling gave faster transistors at constant power density until about 2005; since then extra transistors go into more cores and specialized accelerators, and programs must be parallel to benefit.
  • time=I×CPI×Tc\text{time} = I \times \mathrm{CPI} \times T_c. The instruction count, the CPI and the clock depend on different layers; only their product measures performance.

Code#

The three-instruction program in RARS syntax; it runs in the RARS simulator, which the processor and ISA note introduces:

# a2 = 5 + 7, printed with the print-integer system call
        .text
main:
        addi a0, zero, 5        # 0x00500513
        addi a1, zero, 7        # 0x00700593
        add  a2, a0, a1         # 0x00B50633
        mv   a0, a2             # the system call prints a0
        li   a7, 1              # 1 = print integer
        ecall                   # prints 12
        li   a7, 10             # 10 = exit
        ecall

The fetch–decode–execute loop in Python, for the two instruction formats the program uses. Memory is a dictionary from addresses to 32-bit words; the decoder extracts the fields that the encoding note describes:

mem = {0x00400000: 0x00500513, 0x00400004: 0x00700593, 0x00400008: 0x00B50633}
reg = [0] * 32
pc = 0x00400000
names = {0: 'zero', 10: 'a0', 11: 'a1', 12: 'a2'}
while pc in mem:
    ir = mem[pc]                                  # 1. fetch
    opcode, rd = ir & 0x7F, (ir >> 7) & 0x1F      # 2. decode
    rs1, rs2 = (ir >> 15) & 0x1F, (ir >> 20) & 0x1F
    if opcode == 0x13:                            # addi: rd = rs1 + 12-bit immediate
        imm = (ir >> 20) - ((ir >> 31) << 12)      # the immediate is a signed 12-bit number
        result, text = reg[rs1] + imm, f'addi {names[rd]}, {names[rs1]}, {imm}'
    elif opcode == 0x33:                          # add: rd = rs1 + rs2
        result, text = reg[rs1] + reg[rs2], f'add {names[rd]}, {names[rs1]}, {names[rs2]}'
    reg[rd] = result                              # 3. execute, 4. write back
    print(f'{pc:#010x} {ir:#010x} {text:18} {names[rd]} = {result}')
    pc += 4                                       # 5. next
# 0x00400000 0x00500513 addi a0, zero, 5   a0 = 5
# 0x00400004 0x00700593 addi a1, zero, 7   a1 = 7
# 0x00400008 0x00b50633 add a2, a0, a1     a2 = 12

The performance-equation examples:

def time(I, cpi, f):
    return I * cpi / f

mix = {'arith': (0.5, 1.0), 'mem': (0.3, 2.0), 'branch': (0.2, 1.5)}   # fraction, CPI
cpi = sum(p * c for p, c in mix.values())
print(round(cpi, 3), round(time(2e9, cpi, 3e9), 3))                    # 1.4 0.933
counts = {'arith': 0.8e9, 'mem': 0.6e9, 'branch': 0.4e9}               # after the compiler removes 0.2e9 arithmetic
cycles = sum(n * mix[k][1] for k, n in counts.items())
print(round(cycles / 3e9, 3), round(cycles / sum(counts.values()), 3)) # 0.867 1.444: faster, higher CPI
print(round(time(2e9, 1.4 * 1.4, 4e9), 3))                             # 0.98: a 4 GHz clock with 40 % higher CPI is slower
print(10 * 2e9 / 2, round(time(1e10, 2.5, 3e9), 2))                    # 10000000000.0 8.33: the self-check

The matrix multiplication in C, in the three loop orders. Compile with clang -std=c17 -Wall -Wextra -O0 matmul.c -o matmul. The times depend on the machine and vary by 10–30 % from run to run on a busy one; the comment shows one run on an Apple M1 (8 GB, macOS 26, Apple clang 21):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define N 1024
static double A[N][N], B[N][N], C[N][N];

static double seconds(void) {
    struct timespec t;
    clock_gettime(CLOCK_MONOTONIC, &t);
    return t.tv_sec + 1e-9 * t.tv_nsec;
}

static double multiply(const char *order) {        /* C = A B with the loops nested in the given order */
    memset(C, 0, sizeof C);
    double t0 = seconds();
    if (strcmp(order, "ijk") == 0)                  /* B is walked down a column */
        for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) for (int k = 0; k < N; k++) C[i][j] += A[i][k] * B[k][j];
    else if (strcmp(order, "ikj") == 0)             /* B and C are walked along rows */
        for (int i = 0; i < N; i++) for (int k = 0; k < N; k++) for (int j = 0; j < N; j++) C[i][j] += A[i][k] * B[k][j];
    else                                            /* jki: A and C are walked down columns */
        for (int j = 0; j < N; j++) for (int k = 0; k < N; k++) for (int i = 0; i < N; i++) C[i][j] += A[i][k] * B[k][j];
    return seconds() - t0;
}

int main(void) {
    for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++) {
            A[i][j] = rand() / (double)RAND_MAX;
            B[i][j] = rand() / (double)RAND_MAX;
        }
    const char *orders[] = {"ijk", "ikj", "jki"};
    double check = 0;
    for (int r = 0; r < 3; r++) {
        double t = multiply(orders[r]);
        if (r == 0) check = C[N / 2][N / 3];
        printf("%s %.1f s, same result: %d\n", orders[r], t, check == C[N / 2][N / 3]);
    }
    return 0;
}
/* ijk 5.4 s, same result: 1
   ikj 1.5 s, same result: 1
   jki 6.4 s, same result: 1 */

Next#

The memory of the stored-program computer holds only numbers, and so far we have written them without asking how: 0x00B50633, 5, 7, the 13 bytes of "hello, world\n". The next note opens the lowest layer that software sees: bits, bytes and hexadecimal, how unsigned and negative integers are encoded so that one adder serves both, what happens when a result does not fit, and in which order the bytes of a word are stored in memory.

References#

  • A. Tatarnikov. Computer Architecture and Operating Systems (HSE), lecture 1: introduction and motivation.
  • D. A. Patterson, J. L. Hennessy. Computer Organization and Design, RISC-V Edition, 2nd ed. Morgan Kaufmann, 2020. Chapter 1: §1.3 (below your program), §1.4 (under the covers), §1.6 (performance and the classic CPU performance equation), §1.7 (the power wall), §1.8 (the switch from uniprocessors to multiprocessors).
  • J. L. Hennessy, D. A. Patterson. Computer Architecture: A Quantitative Approach, 6th ed. Morgan Kaufmann, 2019. §1.1 and Figure 1.1 (growth of processor performance by period), §1.5 (trends in power and energy), §1.9 (the processor performance equation).
  • R. E. Bryant, D. R. O’Hallaron. Computer Systems: A Programmer’s Perspective, 3rd ed. Pearson, 2016. Chapter 1 (a tour of computer systems, following the hello program).
  • J. von Neumann. First Draft of a Report on the EDVAC. Moore School of Electrical Engineering, University of Pennsylvania, 30 June 1945; reprinted in IEEE Annals of the History of Computing, 15(4), 1993.
  • G. E. Moore. Cramming more components onto integrated circuits. Electronics, 38(8), 1965; reprinted in Proceedings of the IEEE, 86(1), 1998.
  • R. H. Dennard, F. H. Gaensslen, H.-N. Yu, V. L. Rideout, E. Bassous, A. R. LeBlanc. Design of ion-implanted MOSFET’s with very small physical dimensions. IEEE Journal of Solid-State Circuits, 9(5), 1974. Table I (scaling rules).
  • J. Backus. Can programming be liberated from the von Neumann style? Communications of the ACM, 21(8), 1978 (the von Neumann bottleneck).
  • N. P. Jouppi et al. In-datacenter performance analysis of a tensor processing unit. ISCA, 2017.
  • ENIAC and Manchester Baby, Wikipedia (dates, tube count, power, speed, the first stored program).