跳到主要内容

计算机体系结构

大学计算机科学知识点 6

本主题的视频课程 打开视频页面
6:22

计算机体系结构

本课程探讨程序底层的机器,以及它如何实现高速运行。前两个单元介绍约定,也就是指令集,以及遵守这一约定的机器,也就是数据通路。接下来的两个单元介绍如何用流水线和存储层次结构提高速度。最后两个单元介绍它如何连接输入输出设备和其他处理器。所有关于时间的结论都根据给定参数计算得出。

英文讲解 · 可切换中英文字幕

讲义

English

What this course is, and how to use it

This is the sixth course in University Computer Science: computer architecture 计算机体系结构, the machine below the program. It covers how an instruction set is defined, how a datapath carries out each instruction, how a pipeline overlaps instructions, and how memory and input/output keep the processor supplied with data.

A limit, stated once: this is a study course, not a degree. The teaching machine is an original load-store design with 16 registers (R0 is always zero). Every timing claim in this handout is calculated from the stated numbers, and you can calculate it again yourself.

  • Units 6.1–6.2 are the contract and the machine that keeps it.
  • Units 6.3–6.4 make it fast: pipelining and the memory hierarchy.
  • Units 6.5–6.6 connect it: input/output and parallel speedup.

The habit to build: performance is arithmetic, not adjectives. Every speedup in this course is a number you can calculate again.

Instruction set architecture

Why it matters. The instruction set architecture 指令集架构 (ISA) is the contract between the compiler and the hardware. It lists everything the software may rely on, and says nothing about how the hardware is built. Two machines with the same ISA run the same programs.

The underside of an Intel CPU chip on a white background, a flat square covered in a grid of hundreds of small gold contact pads that press onto the motherboard socket
A modern CPU: the whole processor is one small chip (here seen from below, showing the contacts)

The idea. Our teaching ISA follows the RISC 精简指令集 style:

  • every instruction is 32 bits long;
  • it is a load-store 存取体系 architecture: only lw and sw touch memory;
  • there are 16 registers, and R0 always holds zero.

Two formats cover the course:

format fields (bits) example
R-type R 型 opcode(4) | rd(4) | rs(4) | rt(4) | shift(4) | funct(8) add rd, rs, rt
I-type I 型 opcode(4) | rt(4) | rs(4) | pad(4) | immediate(16) lw rt, imm(rs)

In the I-type, the pad field is not used; it keeps the word at 32 bits.

Instruction encodings
Two formats, one width: R-type carries three registers and a function code; I-type trades the third register for a 16-bit immediate

What a 16-bit immediate costs. A 16-bit two's complement immediate covers $-2^{15}$ to $2^{15} - 1$, that is, $-32\,768$ to $32\,767$. So addi R2, R0, 40000 cannot be encoded, and the assembler needs two instructions (load the high half, then add the low half). Memory is byte-addressable 字节寻址 and words are 32 bits, so lw offsets are multiples of $4$. A 16-bit offset reaches a range of $2^{16}$ bytes $= 64$ KiB around the base register.

Worked example 1: encode and decode. The opcodes are add = 1, addi = 2, lw = 3, sw = 4 and beq = 5.

Encode add R3, R1, R2:

opcode rd rs rt shift funct
0001 0011 0001 0010 0000 00000001

Six fields use 28 of the 32 bits; the top 4 bits of the word are zero.

Decode 0010 0100 0001 0000 0000000001111111: opcode 2, rt = 4, rs = 1, pad = 0, and immediate $1111111_2 = 127$. So this is addi R4, R1, 127.

Worked example 2: what R0 gives you.

  • addi R0, R0, 0 is the standard no-op (it does nothing).
  • add R5, R0, R0 sets R5 to zero in one cycle.
  • Comparing with zero (beq R1, R0, loop) needs no constant.

A register that is always zero removes a whole group of instructions. CISC designs kept MOV reg, 0; RISC keeps a wire.

Common mistakes.

  • Reading a 16-bit immediate as unsigned. Branch and offset arithmetic is signed.
  • Expecting add to touch memory. In a load-store design it cannot.
  • Thinking the opcode alone chooses the operation. R-type instructions also need the funct field.

Summary. The ISA is the stable contract. R-type and I-type formats have one fixed width. 16-bit signed immediates reach $\pm 32$ K, and offsets cover 64 KiB of memory. R0 is a wire, not a register you can write.

Datapath and control

Why it matters. The ISA is a set of promises. The datapath 数据通路 is the hardware that keeps them, and control 控制器 sets the switches for each instruction.

The fetch register transfers in order: 1 the PC's address goes to the MAR; 2 the MAR sends the address to memory; 3 the instruction returns to the MDR; 4 the MDR copies it to the CIR; meanwhile the PC is incremented
The register transfers in a fetch: PC → MAR → memory → MDR → CIR, with the PC incremented

The idea. In a single-cycle machine, each instruction takes one clock cycle:

  1. The PC gives an address to the instruction memory (IM).
  2. The register file (RF) reads two source registers.
  3. The ALU 算术逻辑单元 calculates.
  4. The data memory (DM) is read or written, if needed.
  5. The result is written back to a register.
  6. PC + 4, or a branch target, is loaded into the PC.

The control signals are RegWrite, MemRead, MemWrite, MemToReg, ALUSrc and Branch.

Single-cycle datapath
One clock, one instruction: fetch at PC, read registers, compute at the ALU, touch data memory if asked, write back, and choose the next PC

Why the cycle time is set by the slowest path. All the work happens within one clock cycle, so the clock must wait for the longest instruction. That is lw: instruction memory, register read, ALU, data memory, and write back. With our numbers (IM 200 ps, RF read 100 ps, ALU 200 ps, DM 250 ps, wiring 150 ps in total; register writes happen at the end of the cycle):

$$\text{lw path} = 200 + 100 + 200 + 250 + 150 = 900 \text{ ps}$$

So the cycle is $900$ ps, and a program of 100 instructions takes $90\,000$ ps. Making add faster would not help: the whole machine runs at the speed of its slowest instruction.

Worked example 1: the signals for a load. lw R4, 8(R1):

signal value why
RegWrite 1 R4 is written
MemRead 1 data memory is read
MemToReg 1 the register gets the value from memory
ALUSrc 1 the ALU adds the immediate to make the address
Branch 0 no branch
MemWrite 0 memory is not written

Six bits tell the whole story. The same datapath runs every instruction; only the settings change.

Worked example 2: the store is different. sw R5, 12(R1) writes to memory, not to the register file: RegWrite = 0, MemWrite = 1, MemRead = 0, and MemToReg = x ("don't care", because nothing is written back). "Don't care" settings give the designer freedom: whatever the bit is, the instruction behaves in the same way.

Common mistakes.

  • Forgetting that PC + 4 is computed even for branches. The branch target is calculated from PC + 4.
  • Mixing up the meaning of MemToReg = 0 and 1 between different designs.
  • Thinking control runs step by step. It is combinational logic on the opcode and funct fields.

Summary. One shared datapath, with control bits for each instruction. The cycle time is the path of the slowest instruction, usually lw.

Pipelining

Why it matters. In a single-cycle machine, most parts are idle most of the time. Pipelining 流水线 overlaps instructions like a factory assembly line: many more instructions finish each second, for almost the same hardware.

The idea. There are five stages:

  1. IF: fetch;
  2. ID: decode and read registers;
  3. EX: execute;
  4. MEM: memory access;
  5. WB: write back.

Instruction $i+1$ is fetched while instruction $i$ is decoded. Once the pipeline is full, one instruction retires 完成 (finishes) every cycle.

Pipeline timeline
Five instructions through five stages: 9 cycles total, not 25 — the pipe fills once and drains once

The speedup formula. Take $n$ instructions, $k$ stages and a stage time $t$.

  • Without a pipeline: time $= n k t$.
  • With a pipeline: time $= (n + k - 1)\,t$ ($k - 1$ cycles to fill, then one instruction per cycle).

For five instructions and five stages, $25t$ becomes $9t$. For $n = 100$, $500t$ becomes $104t$. As $n$ grows, the speedup gets close to $k$, and the ideal CPI 每条指令周期数 (cycles per instruction) is $1$.

The stage time is set by the slowest stage. With IF 250, ID 150, EX 200, MEM 250 and WB 100 ps, every stage takes $250$ ps. So the pipeline finishes one instruction every $250$ ps, against $900$ ps for the single-cycle machine.

Worked example 1: a RAW hazard.

add R1, R2, R3     # IF in cycle 1, writes R1 in WB (cycle 5)
sub R4, R1, R1     # IF in cycle 2, reads R1 in ID (cycle 3), too early

The sub reads the register file two cycles before add writes it. This is a read-after-write hazard 读后写相关. Forwarding 前递 sends the ALU result of add straight back to the ALU inputs of sub, so no waiting is needed. The exception is a load: in lw R1, … followed by add R3, R1, R2, the pipeline must still stall for one cycle, because the data exists only after the MEM stage.

Worked example 2: CPI with stalls. A program runs $1000$ instructions on a 5-stage pipeline with forwarding. $25\%$ of them are loads, and half of those loads are followed straight away by an instruction that uses the result. Each such pair costs one stall:

$$\text{stalls} = 1000 \times 0.25 \times 0.5 = 125$$

Total cycles $= 1000 + 125 + 4 = 1129$, so CPI $= 1129 / 1000 = 1.129$. The fill cost ($4$ cycles) matters less and less as $n$ grows.

Common mistakes.

  • Multiplying stages by instructions instead of using $n + k - 1$.
  • Thinking forwarding fixes a load followed by a use. One bubble remains.
  • Forgetting that branches change the PC late. When a branch is taken, the wrong next instruction has already been fetched (in our design: 1 bubble, resolved in EX).

Summary. $n + k - 1$ cycles for $n$ instructions; ideal CPI 1. Forwarding removes ALU hazards; a load followed by a use costs one stall; a taken branch costs one bubble. The speedup approaches the number of stages.

Memory hierarchy

Why it matters. The processor wants data in a nanosecond; cheap memory answers in hundreds of nanoseconds. The memory hierarchy 存储层次结构 puts small, fast memory on top of big, slow memory and lets locality 局部性 make it work.

The opened circuit board of a solid-state drive on a white background: a large black flash-memory chip on the left, a smaller controller chip, many tiny components, and a flat SATA connector along the bottom edge — no platters or moving parts
Inside an SSD: data is stored in flash memory chips, with no moving parts (compare the hard disk above)
A RAM module (DIMM): a circuit-board stick with a black heat-spreader over the memory chips and a gold-edged connector that plugs into a slot on the motherboard
A RAM module (DIMM) plugs into the motherboard as the computer's fast main memory
A pyramid: registers at the top, then cache, then RAM (main memory), then secondary storage at the base; towards the top is faster and smaller, towards the base is slower and larger
The memory hierarchy: each level trades speed for size and cost

The idea. A direct-mapped cache 直接映射缓存 puts each memory block in exactly one place (line). A 32-bit address is split into three parts: tag 标记 | index 索引 | offset 块内偏移. Our course cache is $4$ KiB with $16$-byte lines:

  1. $4096 / 16 = 256$ lines.
  2. Offset: $16 = 2^4$, so $4$ bits.
  3. Index: $256 = 2^8$, so $8$ bits.
  4. Tag: the rest, $32 - 12 = 20$ bits.
Address decomposition and hierarchy
The 32-bit address splits by the cache geometry; below it, the hierarchy each level feeds

Average memory access time. The average memory access time 平均访存时间 (AMAT) is

$$\text{AMAT} = t_{\text{hit}} + p_{\text{miss}} \times t_{\text{penalty}}$$

With an L1 hit time of $1$ cycle, a miss ratio of $2\%$ and a miss penalty of $100$ cycles, AMAT $= 1 + 0.02 \times 100 = 3$ cycles. A miss ratio of only $2\%$ makes memory $3$ times slower; this is why the hierarchy depends completely on locality. Halve the miss ratio to $1\%$ and AMAT $= 2$. AMAT grows in a straight line with the miss ratio.

Worked example 1: where does an address go? Take the address $0x000004A8$. Its low 12 bits are $0100\,1010\,1000$.

  • Offset: the low 4 bits, $1000_2 = 8$ (byte 8 of its line).
  • Index: the next 8 bits, $0100\,1010_2 = 74$ (line 74 of 256).
  • Tag: the top 20 bits.

Each address has one possible line. Any other block that maps to line 74 evicts 驱逐 (throws out) this one. A direct-mapped cache is fast because it needs only one comparison; the price is these conflict misses.

Worked example 2: locality in practice. Scan a $64 \times 64$ array of 4-byte ints, with 16-byte lines (4 ints per line).

  • Row by row (row-major): the first access to each line misses and the next three hit, so the miss rate is $1/4 = 25\%$.
  • Column by column: each step jumps 64 ints ($256$ bytes) to a new line, so every access misses: $100\%$.

AMAT is $1 + 0.25 \times 100 = 26$ cycles against $1 + 1 \times 100 = 101$ cycles: the same array and the same cache, nearly four times slower. How data is laid out is a performance feature.

Common mistakes.

  • Working out the index width from the cache size without dividing by the line size. The index counts lines, not bytes.
  • Expecting a bigger cache to fix a bad access pattern. Data still moves one line at a time.
  • Mixing up misses per access and misses per instruction. They differ by the number of memory accesses per instruction.

Summary. Split the address by the cache shape (tag | index | offset). AMAT $= t_{\text{hit}} + m \times p$. A direct-mapped cache gains speed and pays with conflict misses. Locality, reusing data and using data that is close together, is what makes the hierarchy work.

Input/output

Why it matters. A machine that cannot communicate is useless. Input/output is where microseconds meet milliseconds, and the three ways of moving data trade the processor's attention against throughput.

The idea.

  • Programmed I/O 程序控制 I/O (polling): the processor checks a status register again and again.
  • Interrupt-driven I/O 中断驱动 I/O: the device sends a signal; the processor saves its state and runs a handler.
  • DMA 直接存储器访问 (direct memory access): a DMA controller moves a whole block and interrupts once at the end.
Three I/O paths
Polling burns the core; interrupts charge per event; DMA charges once per block

What each style costs. A device flag changes every $2$ µs. One poll costs $50$ cycles at $250$ ps per cycle, which is $12.5$ ns.

  • Polling: to react as fast as possible, the processor polls without stopping, $2\,\mathrm{µs} / 12.5\,\mathrm{ns} = 160$ polls per event, and all but one are wasted. That is $160 \times 50 = 8\,000$ cycles for each word.
  • Interrupts: the cost falls to the handler cost, $200$ cycles per word (save state, read, restore).
  • DMA: moving $1024$ words costs one setup of $500$ cycles plus one completion interrupt of $200$ cycles, so $700 / 1024 = 0.68$ cycles per word.

DMA needs about 300 times less processor attention per word than interrupts.

Worked example 1: choosing the style.

device best style why
keyboard (about 5 characters per second) interrupts one event per key press, $200$ cycles each: tiny; polling would waste the whole processor
disk, $4$ MiB block at $2$ GB/s DMA even one interrupt per word would swamp the processor
sensor read exactly every $2$ µs polling simple and honest: the polling rate is the sample rate

Worked example 2: the interrupt bill. Each interrupt has $200$ cycles of overhead (save state, find the handler, restore). Receiving $1024$ words with one interrupt per word costs $1024 \times 200 = 204\,800$ cycles of overhead. The same block by DMA costs $700$ cycles in total. The data moved is the same, but the processor's bill differs by a factor of about $290$. Moving data in blocks is not a small optimisation: it changes the design.

Common mistakes.

  • Polling inside an interrupt handler (mixing up the two styles).
  • Forgetting that DMA needs care with the cache: the DMA controller and the processor both use memory.
  • Mixing up interrupt latency (the time until the handler starts) and throughput (words per second).

Summary. Polling: simple, but uses up the processor. Interrupts: a cost per event, with handler overhead for each word. DMA: a cost per block, one interrupt per block, so the processor's attention per word falls by hundreds of times.

Parallelism and performance

Why it matters. Clock speeds stopped rising. Instead, processors got wider and there are more of them. To read a speedup claim today, you need Amdahl's law.

A graphics card on a white background, showing the large cooling fan over the GPU and the gold edge connector that plugs into the motherboard
A graphics card: its GPU runs the same instruction on many data items at once (SIMD)

The idea. A program has a serial part and a part $f$ that can run in parallel. On $p$ processors, Amdahl's law gives

$$\text{Speedup} = \frac{1}{(1 - f) + f / p}$$

The serial part never gets shorter.

Amdahl speedup curves
Speedup against processor count for parallel fractions 0.5, 0.9 and 0.99: the serial fraction caps every curve

The ceiling. As $p$ grows without limit, the speedup approaches $1 / (1 - f)$, which depends only on the serial part. With $f = 0.9$:

$p$ speedup
8 $1 / (0.1 + 0.1125) = 4.71$
16 $1 / (0.1 + 0.0563) = 6.40$
unlimited $1 / 0.1 = 10$

The first eight processors raise the speedup from $1$ to $4.71$; the next eight add only $1.69$ more. With $f = 0.99$ the ceiling is $100$, but even a speedup of $50$ needs $p = 99$: $1/(0.01 + 0.99/99) = 50.0$ exactly. These diminishing returns are built into the formula.

Worked example 1: pricing a speedup. On one core, a render spends $36$ s on compositing (serial) and $64$ s on shading (parallel), so $f = 64/100 = 0.64$.

  • $p = 4$: speedup $= 1/(0.36 + 0.16) = 1.92$; run time $= 100 \times 0.52 = 52.0$ s.
  • $p = 8$: speedup $= 1/(0.36 + 0.08) = 2.27$; run time $44.0$ s.

The serial compositing now takes most of the time. The next thing to buy is a better algorithm, not a bigger machine.

Worked example 2: parallelism inside one core. Even before multiple cores, the pipeline is a kind of parallelism: the 5-stage machine overlaps five instructions. This is instruction-level parallelism 指令级并行 (ILP). With simultaneous multithreading 同时多线程 (SMT), one core fills pipeline bubbles with instructions from another thread; the hazard rules of unit 6.3 still apply to each thread. So there are three levels: ILP inside a core, several threads per core, several cores per chip. Amdahl's law applies at every level.

Common mistakes.

  • Reporting the ideal speedup instead of the measured one. Using $p$ as the speedup assumes $f = 1$.
  • Treating a $10\%$ serial part as harmless. It limits every machine you will ever buy to a speedup of $10$.
  • Comparing speedups with different starting points. The one-core time must be the same program on the same machine, with one core in use.

Summary. Speedup $= 1/((1-f) + f/p)$, with a ceiling of $1/(1-f)$. The serial part dominates at large scale. ILP, threads and cores are three levels of one ladder, and Amdahl's law applies to all of them.

词汇
English 中文 拼音
computer architecture/kəmˈpjuːtə ˈɑːkɪtektʃə/ 计算机体系结构 jì suàn jī tǐ xì jié gòu
instruction set architecture/ɪnˈstrʌkʃn set ˈɑːkɪtektʃə/ 指令集架构 zhǐ lìng jí jià gòu
RISC/rɪsk/ 精简指令集 jīng jiǎn zhǐ lìng jí
load-store/ləʊd stɔː/ 存取体系 cún qǔ tǐ xì
byte-addressable/baɪt əˈdresəbl/ 字节寻址 zì jié xún zhǐ
datapath/ˈdeɪtəpæθ/ 数据通路 shù jù tōng lù
control/kənˈtrəʊl/ 控制器 kòng zhì qì
ALU/ˌeɪ el ˈjuː/ 算术逻辑单元 suàn shù luó jí dān yuán
pipelining/ˈpaɪplaɪnɪŋ/ 流水线 liú shuǐ xiàn
retires/rɪˈtaɪəz/ 完成 wán chéng
CPI/ˌsiː piː ˈaɪ/ 每条指令周期数 měi tiáo zhǐ lìng zhōu qī shù
read-after-write hazard/riːd ˈæftə raɪt ˈhæzəd/ 读后写相关 dú hòu xiě xiāng guān
forwarding/ˈfɔːwədɪŋ/ 前递 qián dì
memory hierarchy/ˈmeməri ˈhaɪərɑːki/ 存储层次结构 cún chǔ céng cì jié gòu
locality/ləʊˈkælɪti/ 局部性 jú bù xìng
direct-mapped cache/daɪˈrekt mæpt kæʃ/ 直接映射缓存 zhí jiē yìng shè huǎn cún
tag/tæɡ/ 标记 biāo jì
index/ˈɪndeks/ 索引 suǒ yǐn
block offset/blɒk ˈɒfset/ 块内偏移 kuài nèi piān yí
average memory access time/ˈævrɪdʒ ˈmeməri ˈækses taɪm/ 平均访存时间 píng jūn fǎng cún shí jiān
evicts/ɪˈvɪkts/ 驱逐 qū zhú
programmed I/O/ˈprəʊɡræmd aɪ əʊ/ 程序控制 I/O chéng xù kòng zhì I/O
interrupt-driven I/O/ˈɪntərʌpt ˈdrɪvən aɪ əʊ/ 中断驱动 I/O zhōng duàn qū dòng I/O
DMA/ˌdiː em ˈeɪ/ 直接存储器访问 zhí jiē cún chǔ qì fǎng wèn
instruction-level parallelism/ɪnˈstrʌkʃn ˈlevl ˈpærəlelɪzəm/ 指令级并行 zhǐ lìng jí bìng xíng
SMT/ˌes em ˈtiː/ 同时多线程 tóng shí duō xiàn chéng
R-type/ɑː taɪp/ R 型 R xíng
I-type/aɪ taɪp/ I 型 I xíng

该知识点的互动课程

逐步完成,配合即时检查练习。

更多 大学计算机科学 知识点

登录或创建账户

IGCSE, A-Level & AP