A Level Computer Science · Chapter 1 · Component 01: Computer systems
A processor runs every program by repeating one simple cycle, fetch, decode and execute, and its speed depends on its clock, its cores and its cache.
This chapter teaches what is inside a processor and how its registers move data during the fetch-decode-execute cycle. It then teaches how clock speed, multiple cores and cache memory change performance, and how to calculate each effect.
In this chapter · jump to a section
Start here
Your route through this chapter
By the end of this chapter you will be able to:
- describe the control unit, the arithmetic logic unit, the registers, the clock and the three buses
- explain the role of the PC, MAR, MDR, CIR and accumulator
- trace the fetch-decode-execute cycle as a sequence of register transfers
- compare von Neumann, Harvard and contemporary architectures
- calculate times from clock speeds, and explain why clock speed alone does not decide performance
- use Amdahl's law to predict the speed-up from multiple cores
- calculate the average memory access time with a cache, and explain how cache improves performance
Time: three sessions, about 4 hours, plus the programming task.
You need first: binary and hexadecimal from Number systems and binary arithmetic. The Little Man Computer in Assembly language and addressing modes helps, but this chapter explains what you need.
The big picture
The big picture
When you open an app, your processor carries out billions of tiny steps every second. Each step is simple: copy a number, add two numbers, compare a result with zero, jump to another instruction. What makes a computer powerful is not the cleverness of any single step, but how many it can do, how quickly, and without error.
Every one of those steps follows the same pattern. The processor fetches the next instruction from memory, decodes it to find out what it means, and executes it. Then it does the same again, for as long as the computer is switched on. This is the fetch-decode-execute cycle, and understanding it explains almost everything about how a processor works.
Inside the processor, a few small, very fast stores called registers hold the values the cycle needs right now. One holds the address of the next instruction. Others hold the address being read, the data that arrived, and the instruction being decoded. Watching these registers change, stage by stage, is how you trace the cycle.
The processor is connected to main memory by buses, sets of parallel wires that carry addresses, data and control signals. It is driven by a clock, which sends a steady stream of pulses. Each pulse lets the processor take one more step.
Making a processor faster can be done in three main ways. The clock can tick faster, so more steps happen each second. There can be several cores, each running its own stream of instructions. And a cache can keep recently used data close to the processor, so it does not wait for slow main memory.
None of these is as simple as it sounds. A faster clock makes the chip hotter. Extra cores only help if the work can be split up. A cache only helps when the data needed is already in it. This chapter teaches you to calculate each effect, so you can say how much each change really helps.
Throughout the chapter, numbers are given with the units engineers use. Clock speeds are in gigahertz, where 1 GHz is 10⁹ pulses a second. Times are in nanoseconds, where 1 ns is 10⁻⁹ seconds. Keeping track of these powers of ten is half the work of every performance calculation.
Section 1
Inside the processor
The control unit and the ALU
The processor, or central processing unit, has two main working parts. The control unit, or CU, directs everything. It decodes each instruction and sends control signals to the other parts, telling them what to do and when. It also manages the flow of data between the processor, memory and the input and output devices.
The arithmetic logic unit, or ALU, does the calculations. It carries out arithmetic, such as addition and subtraction, and logical operations, such as AND, OR and comparisons. The result of a comparison, such as whether a value is zero or negative, is recorded in a status register, so that a later branch instruction can test it.
The control unit works through a sequence of control signals for every instruction. For a load, it must signal memory to read, then signal the right registers to accept the value. In some processors these sequences are wired directly into the circuits. In others they are stored as tiny programs called microcode, which makes complex instructions easier to add.
Registers
A register is a tiny, extremely fast store inside the processor, holding one value. Registers are far faster than main memory, because they are part of the processor itself. Most processors have some general-purpose registers for working values, and some special-purpose registers with fixed jobs in the fetch-decode-execute cycle.
The special-purpose registers you need to know are the program counter, the memory address register, the memory data register, the current instruction register and the accumulator. Each is described in section 2, where you will see them working.
General-purpose registers hold values that a program is working with, such as a loop counter or a running total. Keeping them in registers rather than main memory makes a program much faster. Compilers work hard to decide which values deserve a register, because there are only a few dozen of them.
The clock
The system clock sends out a regular stream of electrical pulses. Every action in the processor happens in step with these pulses. The number of pulses each second is the clock speed, measured in hertz. A clock speed of 3 GHz means 3 × 10⁹ pulses every second.
The time between two pulses is the clock period. It is found by dividing 1 by the clock speed. At 3 GHz, the period is about 0.33 nanoseconds, which is roughly the time light takes to travel 10 centimetres.
Worked example 1: the clock period
A processor runs at 2 GHz. Find its clock period in nanoseconds.
| Working | Reason |
|---|---|
| 2 GHz = 2 × 10⁹ pulses per second | The prefix giga means a thousand million |
| Period = 1 ÷ (2 × 10⁹) seconds | The period is the time for one pulse |
| = 5 × 10⁻¹⁰ seconds | Divide one by the clock speed |
| = 0.5 nanoseconds | One nanosecond is 10⁻⁹ seconds |
The clock also keeps the parts of the computer in step with each other. Without it, a register might try to read a value before the ALU had finished producing it. Each clock pulse marks the moment when values are safely ready to move on to the next stage.
Buses
A bus is a set of parallel wires that carries signals between the parts of a computer. There are three. The address bus carries memory addresses from the processor to memory, so it only carries signals one way. The data bus carries data and instructions in both directions. The control bus carries control signals, such as read, write and clock pulses, in both directions.
Common mistake: thinking the address bus carries data both ways. Only the processor ever puts an address on the address bus, so it is one-way, from processor to memory. Data travels in both directions, but on the data bus, not the address bus.
The width of a bus matters. An address bus of n wires can carry 2ⁿ different addresses, so it decides how much memory the processor can reach directly. A wider data bus moves more bits in each transfer, so data reaches the processor faster.
The processor's word size is the number of bits it handles in one operation, such as 32 or 64. It usually matches the width of the registers and the data bus. A 64-bit processor can add two 64-bit numbers in one step, where a 32-bit processor would need two.
Worked example 2: bus widths
A processor has a 32-bit address bus and a 64-bit data bus. How many memory locations can it address, and how many bytes does each data transfer move?
| Working | Reason |
|---|---|
| Addresses = 2³² | Each address wire carries one bit of the address |
| 2³² = 4,294,967,296 locations | That is 4 GiB if each location holds a byte |
| A 64-bit data bus carries 64 bits at once | One bit per wire |
| 64 ÷ 8 = 8 bytes per transfer | There are 8 bits in a byte |
Buses are shared. Every device that talks to the processor, from memory to the graphics card, uses the same buses, and only one transfer can happen on a bus at a time. The control bus carries the signals that decide whose turn it is, and when a transfer starts and ends.
The three parts of a processor work as a team on every instruction. The control unit decides what should happen, the registers hold the values involved, and the ALU does any calculation. Main memory supplies the instructions and data, and the buses carry them back and forth.
Check yourself. Which part of the processor decides whether a value is negative, and where is the answer kept?
Show the answer
The ALU carries out the comparison or subtraction. The result, such as a negative flag, is kept in the status register, so a branch instruction can test it afterwards.
Section 2
Registers and the fetch-decode-execute cycle
The special-purpose registers
The program counter, or PC, holds the address of the next instruction to be fetched. The memory address register, or MAR, holds the address of the memory location about to be read from or written to. The memory data register, or MDR, holds the data or instruction just read from memory, or about to be written.
The current instruction register, or CIR, holds the instruction currently being decoded and executed. The accumulator, or ACC, holds the results of calculations done by the ALU. Some processors have many general-purpose registers instead of a single accumulator, but the idea is the same.
Common mistake: confusing the MAR with the MDR. The MAR always holds an address, the place to look. The MDR holds the contents, what was found there or what is to be stored. Writing data into the MAR, or an address into the MDR, mixes up where with what.
The fetch stage
The fetch stage brings the next instruction into the processor. The address in the PC is copied into the MAR. The control unit sends a read signal, and the instruction at that address travels along the data bus into the MDR. The PC is increased by 1, so that it points to the following instruction. Finally, the instruction is copied from the MDR into the CIR.
Common mistake: thinking the PC is increased after execution. The PC is increased during the fetch stage, as soon as its value has been copied to the MAR. By the time the instruction is executed, the PC already points to the next one. A branch works by overwriting that new value.
The fetch stage is the same for every instruction. Only the decode and execute stages differ, depending on what the instruction asks for. That is why a trace of the cycle always begins with the same four transfers, whatever the program.
The decode and execute stages
In the decode stage, the control unit splits the instruction in the CIR into its opcode and its operand, and works out what to do. In the execute stage, the instruction is carried out. A load instruction puts its address into the MAR, reads the value into the MDR and copies it to the accumulator. A store instruction puts the accumulator's value into the MDR and writes it to memory.
Figure 1.1 runs a short program, LDA five, ADD six, STA seven, one stage at a time. Step through and watch which registers change at each stage. Then switch on the wrong model, which swaps the jobs of the MAR and MDR.
The fetch-decode-execute cycle
- Stage
- execute
- Program counter
- 1
- Accumulator
- 5
Worked example 3: fetching and executing a load
A program starts with LDA five, stored as 504 in mailbox 0, where mailbox 4 holds 5. Give the registers after the fetch and after the execute.
| Working | Reason |
|---|---|
| Fetch: MAR ← PC = 0, then MDR ← memory[0] = 504 | The instruction is read from the address in the PC |
| PC ← 1 and CIR ← 504 | The PC moves on; the instruction goes to the CIR |
| Decode: 504 means LDA 4 | The opcode is 5 and the address is 4 |
| Execute: MAR ← 4, MDR ← 5, ACC ← 5 | The value at address 4 is loaded into the accumulator |
Worked example 4: an add and a store
Continue the program: ADD six (105) and STA seven (306), where mailbox 5 holds 6. Give the accumulator and the final contents of mailbox 6.
| Working | Reason |
|---|---|
| Fetch ADD: MAR 1, MDR 105, PC 2, CIR 105 | The same fetch steps as before |
| Execute: MAR ← 5, MDR ← 6, ACC ← 5 + 6 = 11 | The ALU adds the MDR to the accumulator |
| Fetch STA: MAR 2, MDR 306, PC 3, CIR 306 | The third instruction is fetched |
| Execute: MAR ← 6, MDR ← 11, then memory[6] ← 11 | For a store, the MDR holds the data to write |
The cycle repeats for every instruction. A real processor runs this cycle billions of times each second, and every program, however complex, is made of nothing but these simple steps. A branch instruction changes the pattern only by writing a new address into the PC during execution, so the next fetch comes from somewhere else.
Interrupts
An interrupt is a signal that something needs the processor's attention, such as a key being pressed or a printer running out of paper. At the end of each cycle, the processor checks for interrupts. If one is waiting and has a high enough priority, the current register values are saved on a stack. The address of an interrupt service routine is then loaded into the PC.
When the routine finishes, the saved values are restored, and the interrupted program carries on exactly where it stopped. Interrupts let a computer respond quickly to events without wasting time checking every device over and over again.
Interrupts have priorities. A failing power supply matters more than a key press, so its interrupt is handled first. While an interrupt service routine runs, interrupts of lower priority wait, but a higher-priority interrupt can interrupt the routine itself. The saved register values on the stack let each one return to the right place.
Without interrupts, the processor would have to keep asking every device whether it needed attention, which is called polling. Polling wastes cycles when nothing is happening and can respond slowly when something does. Interrupts let devices speak up only when they need to.
Tracing the registers by hand is a skill examiners test often. The trick is to treat each stage as a short list of copies: from one register to another, from memory to a register, or from a register to memory. Writing each copy as an arrow, such as MAR ← PC, keeps the order clear.
Check yourself. After the fetch stage of the instruction at address 7, what does the PC hold, and why?
Show the answer
The PC holds 8. During the fetch, the address 7 is copied to the MAR and the PC is then increased by 1. So it already points to the next instruction while address 7 is decoded and executed.
Section 3
Processor architectures
The von Neumann architecture
In the von Neumann architecture, programs and data are both stored in the same main memory, and they travel along the same buses. This is the stored-program concept: a program is just data that happens to be instructions, so it can be loaded, changed and run like any other data.
The design is simple and flexible, and almost every general-purpose computer uses it. Its weakness is that an instruction and a piece of data cannot be fetched at the same moment, because they share one bus. The processor often has to wait, which is called the von Neumann bottleneck.
Because programs are stored as data, a computer can load a new program from disk and run it. A compiler can even write a program that another program then runs. This flexibility is what makes a general-purpose computer general. It also means that a fault which overwrites instructions can make a program behave unpredictably.
The Harvard architecture
In the Harvard architecture, instructions and data are kept in separate memories, with separate buses. The processor can fetch the next instruction while it reads or writes data, so it does not have to wait. The two memories can also be different sizes and types, such as read-only memory for a fixed program.
Common mistake: thinking Harvard architecture stores data and instructions together. Harvard architecture keeps them in physically separate memories with their own buses. Storing them together, in one memory on one bus, is the von Neumann design.
Harvard architecture is common in embedded systems and digital signal processors, such as those in washing machines, cars and audio equipment. These devices run one fixed program, often from read-only memory, and need fast, predictable timing.
Contemporary architectures
Modern processors mix the two. Main memory holds programs and data together, as in von Neumann, so any program can be loaded and run. Inside the processor, though, the fastest level of cache is split into an instruction cache and a data cache, as in Harvard. So the processor gets the flexibility of one design and much of the speed of the other.
Modern processors also add other features beyond both models. They can be pipelined, with several instructions at different stages at once, and they have several cores. Pipelining and processor types are taught in Types of processor, input, output and storage.
The von Neumann bottleneck gets worse as processors get faster, because memory speeds have improved much more slowly than processor speeds. Caches, wider buses and split instruction and data caches are all ways of easing it, which is why modern designs mix the two architectures.
Worked example 5: the cost of a shared bus
A von Neumann processor needs one bus cycle to fetch an instruction and one more to read its data. A Harvard processor does both at once. How many bus cycles do 1,000 load instructions take on each?
| Working | Reason |
|---|---|
| Von Neumann: 2 bus cycles per load | The fetch and the data read share one bus |
| 1,000 × 2 = 2,000 bus cycles | Every load needs both transfers in turn |
| Harvard: 1 bus cycle per load | The fetch and the data read overlap |
| 1,000 bus cycles, half as many | Separate buses remove the waiting |
Architectures are chosen to fit the job. A laptop must run any program the user installs, so it needs von Neumann flexibility. A dedicated controller runs one program for its whole life, so it can use separate, fixed memories and gain speed and reliability.
Check yourself. Why does a washing machine's controller suit the Harvard architecture?
Show the answer
It runs one fixed program, which can sit in its own read-only instruction memory. Separate memories and buses let it fetch instructions and read sensor data at the same time, giving fast, predictable timing.
Section 4
Clock speed
More cycles each second
A faster clock gives more cycles each second, so a processor can carry out instructions more quickly. If a task needs a fixed number of clock cycles, the time it takes is the number of cycles divided by the clock speed. Doubling the clock speed halves the time.
Worked example 6: time from clock speed
A task needs 6 × 10⁹ clock cycles. How long does it take at 3 GHz, and at 2 GHz?
| Working | Reason |
|---|---|
| Time = cycles ÷ clock speed | Each second gives that many cycles |
| At 3 GHz: 6 × 10⁹ ÷ 3 × 10⁹ = 2 seconds | Divide the cycles by the speed |
| At 2 GHz: 6 × 10⁹ ÷ 2 × 10⁹ = 3 seconds | Fewer cycles each second take longer |
| The faster clock saves 1 second, a third of the time | Time is inversely proportional to speed |
Clock speed also affects how quickly a processor responds. In a game, the time between pressing a button and seeing a result depends on how many cycles the work needs and how fast those cycles pass. A faster clock shortens that delay as long as the work runs on one core.
Why clock speed is not everything
Clock speed only measures cycles, not work. Different processors do different amounts of work per cycle. A newer design might complete two instructions per cycle where an older one needs two cycles per instruction. So a 3 GHz processor of one design can be slower than a 2.5 GHz processor of another.
Common mistake: thinking a higher clock speed always means a faster processor. Clock speed counts pulses, but processors differ in how much they do per pulse, how many cores they have and how much cache they use. Comparing clock speeds only makes sense between processors of the same design.
Faster clocks also cause problems. Each pulse switches millions of transistors, which produces heat, so a faster clock means a hotter chip. Above a certain speed, the chip cannot be cooled well enough. This is one reason clock speeds have stayed around 3 to 5 GHz for years, while designers have added cores instead.
Overclocking means running a processor faster than its rated speed. It can improve performance, but it produces more heat, may make the processor unstable and can shorten its life. Many processors also slow their own clocks when idle, to save power and battery life.
Performance is often measured by how many instructions a processor completes each second, rather than by clock speed. A processor that completes two instructions every cycle at 2 GHz manages 4 × 10⁹ instructions a second. One that needs two cycles per instruction at 3 GHz manages only 1.5 × 10⁹. The slower clock wins.
Clock speed is still the right measure when comparing two settings of the same processor. Suppose a laptop's processor runs at 1.6 GHz on battery and 3.2 GHz on mains power. A task limited by the processor will then take roughly twice as long on battery. Only the clock has changed, so this comparison is a fair one. Everything else about the processor stays exactly the same.
Check yourself. A program takes 8 seconds at 2 GHz. If nothing else changes, how long does it take at 4 GHz?
Show the answer
The clock is twice as fast, so the same number of cycles takes half the time: 4 seconds. This assumes nothing else, such as memory speed, limits the program.
Section 5
Multiple cores
What a core is
A core is a complete processing unit, with its own control unit, ALU and registers. A multicore processor has several cores on one chip, sharing main memory and often some cache. Each core can run its own stream of instructions at the same time as the others, which is called parallel processing.
Multicore processors became common because clock speeds hit a limit. Making one core faster meant a hotter chip, but adding a second core of the same speed could, in principle, double the work done without raising the clock. Most phones, laptops and desktops now have between 4 and 16 cores.
Amdahl's law
More cores only help with work that can be split into independent parts. Some work must happen in order, step after step, and that part runs on one core however many there are. Amdahl's law says how much faster a program can become when a fraction p of it runs in parallel on n cores.
Derivation: Amdahl's law
Suppose a program takes time T on one core, and a fraction p of that time is work that can be shared out. The rest, a fraction 1 − p, must run on one core. With n cores, the parallel part takes p T ÷ n, so the new time is this.
The speed-up is the old time divided by the new time. The T cancels, so the speed-up depends only on p and n.
As n grows, p ÷ n shrinks towards 0, so the speed-up can never exceed 1 ÷ (1 − p). For p = 0.8, that limit is 5, however many cores are added.
Common mistake: thinking n cores make a program n times faster. Only the parallel part of the work is shared out. The part that must run in order takes just as long on one core as on many. So the speed-up is always less than n, with a limit set by that serial part.
In practice the parallel fraction is found by measurement. A programmer times the program on one core and on several, then works backwards through Amdahl's law. A program that speeds up 1.5 times on 2 cores has a parallel fraction of about two thirds, which shows how much is worth gaining from more.
Worked example 7: speed-up from four cores
A program takes 20 seconds on one core, and 80% of its work can run in parallel. Find the speed-up and the time on 4 cores.
| Working | Reason |
|---|---|
| S = 1 ÷ ((1 − 0.8) + 0.8 ÷ 4) | Substitute p = 0.8 and n = 4 |
| = 1 ÷ (0.2 + 0.2) = 1 ÷ 0.4 = 2.5 | The serial and parallel parts each take 0.2 |
| Time = 20 ÷ 2.5 = 8 seconds | Divide the old time by the speed-up |
| 4 cores give 2.5 times the speed, not 4 | The serial 20% still runs on one core |
Worked example 8: the limit of more cores
For the same program, what is the greatest possible speed-up, and what speed-up do 16 cores give?
| Working | Reason |
|---|---|
| Limit = 1 ÷ (1 − 0.8) = 1 ÷ 0.2 = 5 | p ÷ n tends to 0 for very many cores |
| 16 cores: S = 1 ÷ (0.2 + 0.8 ÷ 16) = 1 ÷ 0.25 = 4 | Substitute sixteen cores into the formula |
| Going from 4 to 16 cores only raises 2.5 to 4 | Each extra core helps less |
| The serial part sets a ceiling of 5 times | It can never run faster than one core allows |
Amdahl's law is a warning about expectations. Doubling the number of cores from 8 to 16 can make almost no difference if a program is not highly parallel. Before buying more cores, it is worth asking how much of the work can really be shared.
Writing software for many cores
Programs do not use extra cores automatically. The programmer, the compiler or the operating system must split the work into threads that can run at once. Tasks such as rendering video, where every frame can be worked on separately, split easily. Tasks where each step needs the previous result, such as a long chain of calculations, cannot be split at all.
Cores sharing memory must also coordinate. If two cores change the same value at once, the result can be wrong, so programs use locks to take turns. The time spent coordinating adds to the serial part of the work, which lowers the real speed-up further still.
Even when a single program cannot use many cores, a computer still benefits from them. The operating system can run different programs on different cores at the same time. So a browser, a music player and a virus scan do not slow each other down. That is a different kind of parallelism from splitting one program.
Check yourself. Half of a program's work can run in parallel. What is the most it can ever be sped up by adding cores?
Show the answer
The limit is 1 ÷ (1 − 0.5) = 1 ÷ 0.5 = 2. The serial half always runs at the same speed, so the program can never become more than twice as fast.
Section 6
Cache memory
Why cache is needed
Main memory is much slower than the processor. Reading a value from main memory can take a hundred clock cycles or more, and the processor would spend most of its time waiting. A cache is a small amount of very fast memory, inside or next to the processor, that holds copies of recently used data and instructions.
When the processor needs a value, it checks the cache first. If the value is there, that is a hit, and it arrives quickly. If not, that is a miss: the value must be fetched from main memory, and a copy is placed in the cache for next time. Programs tend to reuse the same data and nearby data, so most accesses are hits.
Cache works because programs are predictable. They tend to use the same data again soon, such as a loop counter, which is called temporal locality. They also tend to use data next to what they just used, such as the next element of an array, which is called spatial locality. When a value is fetched into the cache, its neighbours come with it, ready for the next access.
Levels of cache
Modern processors have several levels of cache. Level 1 cache is the smallest and fastest, often split into instruction and data caches for each core. Level 2 is larger and a little slower. Level 3 is larger again and shared between all the cores. Each level catches some of the misses from the level above.
Cache is expensive, because its memory cells are larger and more complex than those of main memory. That is why it is small: a processor might have a few megabytes of cache and many gigabytes of main memory. Adding more cache helps up to a point, but a larger cache is also slightly slower to search.
Average access time
The effect of a cache is measured by the average memory access time. A hit costs the cache time. A miss costs the cache time, because the cache is checked first, plus the main memory time. The hit rate is the fraction of accesses that are hits.
Derivation: the average memory access time
A fraction h of accesses are hits, each costing the cache time t_c. The other 1 − h are misses, each costing the cache look-up and then the memory time t_m. Weighting each cost by how often it happens gives the average.
Multiplying out, the cache time appears in every access, and the memory time only in the misses.
So the average is the cache time plus the miss rate times the memory time. Halving the miss rate halves the memory part of the average, which is why a small rise in hit rate gives a big improvement.
Common mistake: leaving the cache look-up out of a miss. A miss is only discovered by checking the cache first, so it costs the cache time as well as the memory time. Counting a miss as the memory time alone makes misses look cheaper and the average too low.
Figure 1.2 plots the average access time as the hit rate changes. Move the hit rate and the memory time and read the average. Then switch on the wrong model, which leaves the look-up out of each miss.
Cache hits and average access time
- Average access time
- 12.00 ns
- Speed-up over no cache
- 8.33 times
Cache is managed entirely by hardware. Programs do not ask for data to be cached; the processor decides what to keep, usually discarding whatever has gone unused the longest when space is needed. Writing programs that use data in order, such as walking through an array from start to end, helps the cache do its job.
Worked example 9: average access time
A cache takes 2 ns, main memory takes 100 ns, and the hit rate is 90%. Find the average access time.
| Working | Reason |
|---|---|
| Hits: 0.9 × 2 = 1.8 ns | 90% of accesses take the cache time |
| Misses: 0.1 × (2 + 100) = 10.2 ns | 10% take the look-up plus memory |
| Average = 1.8 + 10.2 = 12 ns | Add the two weighted parts |
| Check: 2 + 0.1 × 100 = 12 ns | The simplified formula agrees |
Worked example 10: raising the hit rate
The hit rate rises from 90% to 98%. Find the new average access time and the improvement.
| Working | Reason |
|---|---|
| New average = 2 + 0.02 × 100 | The miss rate falls to 2% |
| = 2 + 2 = 4 ns | The memory part shrinks to 2 ns |
| 12 ns falls to 4 ns, three times faster | Most accesses no longer wait for memory |
| Without any cache, every access takes 100 ns | The cache makes access 25 times faster |
Cache size is a trade-off between hit rate, speed and cost. A larger cache holds more data, so its hit rate is higher. But it takes slightly longer to search, it uses more of the chip and it costs more. Designers choose sizes for each level that give the best overall average, which is why there are several levels rather than one large cache.
Each core usually has its own level 1 and level 2 caches, and all the cores share level 3. When one core changes a value, the copies in the other cores' caches must be updated or discarded, so that no core uses an old value. Keeping the caches consistent is one of the hardest problems in processor design.
Check yourself. Suppose the cache takes 2 ns and memory takes 100 ns. What hit rate gives an average of 7 ns?
Show the answer
The average is 2 + (1 − h) × 100 = 7, so (1 − h) × 100 = 5 and the miss rate is 0.05. The hit rate must be 95%.
Reference
Key algorithms and definitions
| Term or algorithm | What it means | Example | Cost or rule to learn |
|---|---|---|---|
| Control unit | Decodes instructions and sends control signals | Starts a memory read | Directs the whole cycle |
| ALU | Does arithmetic and logic | Adds the MDR to the ACC | Sets the status flags |
| PC | Address of the next instruction | PC = 1 after the first fetch | Increased during the fetch |
| MAR and MDR | Address to use, and data read or written | MAR 4, MDR 5 | MAR holds where; MDR holds what |
| CIR | Instruction being decoded and executed | CIR = 504 | Split into opcode and operand |
| Buses | Address one way; data and control both ways | 32-bit address bus | 2ⁿ addresses for n wires |
| Von Neumann and Harvard | Shared memory, or separate instruction and data memory | Laptop, washing machine | Harvard avoids the shared-bus wait |
| Clock speed | Cycles per second | 3 GHz | Time = cycles ÷ speed |
| Amdahl's law | Speed-up from n cores | p = 0.8, n = 4 gives 2.5 | Limit 1 ÷ (1 − p) |
| Cache | Small fast memory for recent data | 90% hit rate | t = t_c + (1 − h) t_m |
Programming task
Programming task: modelling processor performance
Aim
Write Python functions that calculate three things: the time for a task at a given clock speed, the speed-up from multiple cores, and the average memory access time. Use them to compare three ways of improving a computer's performance on the same program.
Design
Each function takes its inputs as parameters and returns one number, so it can be tested on its own. The functions check their inputs, raising an error for a hit rate or parallel fraction outside 0 to 1, or for fewer than one core.
A short main program then works out three improvements: doubling the clock speed, moving from 1 to 4 cores, and raising the cache hit rate. It prints each result so they can be compared.
Code
def task_time(cycles, hertz):
if hertz <= 0:
raise ValueError("clock speed must be positive")
return cycles / hertz
def amdahl(p, n):
if not 0 <= p <= 1 or n < 1:
raise ValueError("p must be 0 to 1 and n at least 1")
return 1 / ((1 - p) + p / n)
def average_access(hit_rate, cache_ns, memory_ns):
if not 0 <= hit_rate <= 1:
raise ValueError("hit rate must be 0 to 1")
return hit_rate * cache_ns + (1 - hit_rate) * (cache_ns + memory_ns)
print(task_time(6e9, 3e9))
print(round(amdahl(0.8, 4), 2))
print(round(average_access(0.9, 2, 100), 2))
print(round(average_access(0.98, 2, 100), 2))
The cache function keeps the longer form of the formula, with the look-up added to each miss, because that form shows where every nanosecond comes from. The rounding only tidies the printed output; the functions return the full values.
Testing
| Test | Input | Expected output | Why this test |
|---|---|---|---|
| 1 | task_time(6e9, 3e9) | 2.0 | Matches worked example 6 |
| 2 | amdahl(0.8, 4) | 2.5 | Matches worked example 7 |
| 3 | amdahl(0.8, 16) | 4.0 | Shows the speed-up flattening |
| 4 | amdahl(0, 8) | 1.0 | No parallel work gives no speed-up |
| 5 | average_access(0.9, 2, 100) | 12.0 | Matches worked example 9 |
| 6 | average_access(0.98, 2, 100) | 4.0 | Matches worked example 10 |
| 7 | amdahl(1.5, 4) | ValueError | An impossible fraction is rejected |
Evaluation
All seven tests pass, and the results match the worked examples. Test 4 is a useful check on the formula: with no parallel work, any number of cores leaves the speed unchanged.
The model is simple. Real programs are also limited by memory speed and by the time cores spend coordinating, so real speed-ups are lower. An improvement would add a cost for coordination to the serial part, and combine the three effects into one estimate of run time.
Practice
Practice ladder
Rung 1: Recall and fluency
Q1. State the purpose of the control unit and of the ALU.
Worked solution to Q1
The control unit decodes instructions and sends control signals to direct the other parts of the computer. The ALU carries out arithmetic and logical operations, such as addition and comparisons.
Q2. Describe what the PC, MAR and MDR each hold.
Worked solution to Q2
The PC holds the address of the next instruction to be fetched. The MAR holds the address of the memory location to be read from or written to. The MDR holds the data or instruction read from memory, or to be written to it.
Q3. Explain the difference between the von Neumann and Harvard architectures.
Worked solution to Q3
In the von Neumann architecture, instructions and data share one memory and one set of buses. In the Harvard architecture, they are held in separate memories with separate buses, so an instruction and data can be fetched at the same time.
Rung 2: Application
Q4. A processor has a 24-bit address bus. How many memory locations can it address?
Worked solution to Q4
An address bus of n wires gives 2ⁿ addresses, so the number is 2²⁴. That is 16,777,216 locations, or 16 MiB if each location holds one byte.
Q5. A task needs 9 × 10⁹ cycles. How long does it take at 3 GHz?
Worked solution to Q5
The time is the cycles divided by the clock speed: 9 × 10⁹ ÷ 3 × 10⁹ = 3 seconds. A clock twice as fast would take 1.5 seconds.
Q6. Describe the register transfers in the fetch stage.
Worked solution to Q6
The address in the PC is copied to the MAR. The instruction at that address is read along the data bus into the MDR. The PC is increased by 1, and the instruction is copied from the MDR into the CIR.
Q7. With a 2 ns cache, 100 ns memory and an 80% hit rate, find the average access time.
Worked solution to Q7
The miss rate is 20%, so each access costs the cache time plus a fifth of the memory time. Using t = t_c + (1 − h) × t_m gives 2 + 0.2 × 100 = 22 ns. The longer form, weighting hits and misses separately, agrees: 1.6 + 20.4 = 22 ns.
Rung 3: Analysis
Q8. Find the speed-up on 10 cores of a program that is 90% parallel, and its greatest possible speed-up.
Worked solution to Q8
On 10 cores, S = 1 ÷ (0.1 + 0.9 ÷ 10) = 1 ÷ (0.1 + 0.09) = 1 ÷ 0.19, which is about 5.26. The limit is 1 ÷ 0.1 = 10, which more cores approach but never reach.
Q9. Explain why a 3 GHz processor may be slower than a 2.5 GHz processor.
Worked solution to Q9
Clock speed only counts cycles per second. The 2.5 GHz processor may complete more instructions per cycle, have more cores or have more cache, so it can do more work per second despite its slower clock.
Q10. Explain why the PC already holds the next address while an instruction is executed.
Worked solution to Q10
The PC is increased by 1 during the fetch stage, straight after its value is copied to the MAR. So by the time the instruction is decoded and executed, the PC points to the following instruction, ready for the next fetch.
Q11. A program running on one core takes 30 seconds and is 60% parallel. Find its time on 3 cores.
Worked solution to Q11
The serial part stays at 40% of the old time, while the parallel part is shared between the three cores. So the new time is 30 × (0.4 + 0.2) = 30 × 0.6 = 18 seconds. The speed-up is 30 ÷ 18, about 1.67, well short of 3.
Rung 4: Stretch
Q12. A cache takes 1 ns and memory takes 80 ns. What hit rate is needed for an average access time of 3 ns?
Worked solution to Q12
Set the average access formula equal to the target and solve for the hit rate. Setting 1 + (1 − h) × 80 = 3 gives (1 − h) × 80 = 2, so the miss rate is 2 ÷ 80 = 0.025. The hit rate must therefore be 97.5%.
Q13. Use Amdahl's law to find what parallel fraction p gives a speed-up of exactly 2 on 4 cores.
Worked solution to Q13
Setting 1 ÷ ((1 − p) + p ÷ 4) = 2 gives (1 − p) + p ÷ 4 = 0.5. So 1 − 0.75p = 0.5, giving 0.75p = 0.5 and p = 2 ÷ 3, about 0.67. Two thirds of the work must be parallel.
Q14. A von Neumann processor needs 2 bus cycles per load, and a Harvard one needs 1. A program has 600 loads and 400 other instructions, each needing 1 bus cycle. Compare the totals.
Worked solution to Q14
Von Neumann needs 600 × 2 + 400 × 1 = 1,600 bus cycles. Harvard needs 600 × 1 + 400 × 1 = 1,000. The Harvard design needs 600 fewer bus cycles, a saving of 37.5%.
Exam practice
Exam technique and worked answer workshop
Questions on the fetch-decode-execute cycle reward precise register names and the right order. Write each step as a transfer, such as "the contents of the PC are copied to the MAR", rather than vague phrases such as "the PC goes to memory". Say when the PC is increased.
For performance questions, show the formula, substitute, then give the answer with units. With Amdahl's law, always comment on why the speed-up is less than the number of cores. With cache, show both the hit part and the miss part.
When a question asks how a factor affects performance, explain the mechanism. "More cache is faster" earns little. "More cache raises the hit rate, so fewer accesses wait for slow main memory" earns the marks.
Exam question 1 (4 marks · Paper 01 · about 5 minutes)
(a) State the purpose of the control unit and the ALU. [2]
(b) State which bus is one-way, and explain why. [2]
Mark scheme for exam question 1
- B1 the control unit decodes instructions and sends control signals to coordinate the processor
- B1 the ALU carries out arithmetic and logical operations
- B1 the address bus
- B1 only the processor sends addresses to memory, so signals travel one way
Exam question 2 (5 marks · Paper 01 · about 7 minutes)
Describe the fetch-decode-execute cycle, naming the registers used at each stage.
Mark scheme for exam question 2
- B1 the address in the PC is copied to the MAR
- B1 the instruction at that address is read into the MDR
- B1 the PC is increased by 1
- B1 the instruction is copied to the CIR and decoded by the control unit
- B1 the instruction is executed, for example by the ALU, with any result held in the accumulator
Exam question 3 (5 marks · Paper 01 · about 7 minutes)
Memory address 0 holds the instruction LDA 4, stored as 504, and address 4 holds 5. The PC starts at 0.
(a) Give the contents of the PC, MAR, MDR and CIR after the fetch stage. [3]
(b) Give the contents of the MAR, MDR and accumulator after the execute stage. [2]
Mark scheme for exam question 3
- B1 PC 1
- B1 MAR 0
- B1 MDR 504 and CIR 504
- B1 MAR 4 and MDR 5
- B1 accumulator 5
Exam question 4 (5 marks · Paper 01 · about 7 minutes)
A program takes 20 seconds on one core, and 80% of it can run in parallel.
(a) Calculate the speed-up on 4 cores. [2]
(b) Calculate the time on 4 cores. [2]
(c) Explain why the speed-up is less than 4. [1]
Mark scheme for exam question 4
- M1 1 ÷ (0.2 + 0.8 ÷ 4)
- A1 2.5
- M1 20 ÷ 2.5
- A1 8 seconds
- B1 the 20% of serial work still runs on one core, so it cannot be sped up
Exam question 5 (6 marks · Paper 01 · about 9 minutes)
A school is choosing between two computers for a video-editing class. One has a 4.5 GHz processor with 2 cores and 4 MB of cache. The other has a 3.5 GHz processor with 8 cores and 16 MB of cache. Discuss which is likely to perform better for this use.
Mark scheme for exam question 5
Level 3 (5–6 marks): a balanced discussion of clock speed, cores and cache, each linked to video editing, explaining the mechanism of each. The answer reaches a justified recommendation. It is well organised and uses technical terms accurately.
Level 2 (3–4 marks): a correct explanation of at least two factors, with some link to video editing. The recommendation is limited or not fully justified.
Level 1 (1–2 marks): some relevant points, such as that more cores are faster, with little explanation. The answer may lack structure.
0 marks: no response or no response worthy of credit.
Indicative content:
- a higher clock speed gives more cycles per second, so serial tasks run faster on the first computer
- clock speed alone is not a fair comparison unless the designs are similar
- video editing splits easily, such as working on separate frames, so it is highly parallel
- 8 cores can process many parts at once, giving a large speed-up for parallel work
- Amdahl's law means the gain depends on the parallel fraction, and is less than 8 times
- more cache raises the hit rate, so fewer accesses wait for main memory
- large video files benefit from the bigger cache
- recommendation: the 8-core computer with more cache, because video editing is mostly parallel
Annotated model answer: exam question 5
"The first computer's 4.5 GHz clock gives more cycles each second, so any work that must run step by step will be faster on it. But clock speed only compares fairly between similar designs." (Clock speed, with its limitation.)
"Video editing is very parallel: separate frames can be processed at the same time. The second computer's 8 cores can share this work out, so they give a large speed-up. Amdahl's law means it will still be less than 8 times." (Cores, linked to the task and to Amdahl's law.)
"The 16 MB cache will hold more of the video data close to the processor. That raises the hit rate, so fewer accesses wait for slow main memory." (Cache, with its mechanism.)
"Video editing is mostly parallel and uses large amounts of data. So the 8-core computer with the bigger cache is the better choice, despite its slower clock." (A justified recommendation.)
This answer reaches Level 3 and scores 6 marks. It explains how each factor works and applies all three to video editing before deciding.
Exam question 6 (5 marks · Paper 01 · about 7 minutes)
A cache takes 2 ns and main memory takes 100 ns.
(a) Calculate the average access time for a 90% hit rate. [2]
(b) Calculate the average access time for a 98% hit rate. [2]
(c) Explain why a small rise in hit rate makes a large difference. [1]
Mark scheme for exam question 6
- M1 0.9 × 2 + 0.1 × (2 + 100), or 2 + 0.1 × 100
- A1 12 ns
- M1 2 + 0.02 × 100
- A1 4 ns
- B1 each miss costs about 50 times a hit, so cutting the miss rate from 10% to 2% removes most of the waiting
Exam question 7 (4 marks · Paper 01 · about 5 minutes)
(a) Describe the Harvard architecture. [2]
(b) Give one advantage of the Harvard architecture, and one type of device that uses it. [2]
Mark scheme for exam question 7
- B1 instructions and data are stored in separate memories
- B1 with separate buses
- B1 an instruction and data can be fetched at the same time, so it is faster
- B1 an embedded system, such as a washing machine controller or a digital signal processor
Exam question 8 (6 marks · Paper 02 · about 9 minutes)
Write a function averageAccess(hitRate, cacheTime, memoryTime) that returns the average memory access time. It must reject a hit rate outside 0 to 1. Then state what it returns for (0.9, 2, 100).
Mark scheme for exam question 8
- B1 a function header with the three parameters
- B1 a check that hitRate is between 0 and 1
- B1 an error or message when the check fails
- B1 the hit part, hitRate × cacheTime
- M1 the miss part, (1 − hitRate) × (cacheTime + memoryTime)
- A1 the sum is returned, and the result for (0.9, 2, 100) is 12
Annotated model answer: exam question 8
function averageAccess(hitRate, cacheTime, memoryTime)
if hitRate < 0 OR hitRate > 1 then
print("Invalid hit rate")
return -1
endif
hitPart = hitRate * cacheTime
missPart = (1 - hitRate) * (cacheTime + memoryTime)
return hitPart + missPart
endfunction
The header earns the first mark, and the range check and its message the next two. The hit part earns the fourth mark. The miss part, with the look-up included, earns the method mark, and returning the sum with the result 12 earns the last.
Connections
Synoptic link
The fetch-decode-execute cycle is the same cycle the Little Man Computer runs in Assembly language and addressing modes, with the MAR and MDR made visible. Types of processor, input, output and storage extends this chapter with pipelining, CISC and RISC, and graphics processors.
Interrupts lead into Operating systems and applications, where the operating system's interrupt service routines and scheduler decide which program runs next. Amdahl's law is a performance argument like those in Algorithm analysis and Big O notation: the serial part limits the whole.
Synoptic question 1. A processor runs at 3 GHz, and each memory access that misses the cache waits 100 ns. How many clock cycles does one miss waste?
Answer to synoptic question 1
At 3 GHz the clock period is 1 ÷ (3 × 10⁹) seconds, about 0.33 ns. A 100 ns wait is 100 ÷ 0.333, which is 300 cycles. That is why cache misses hurt so much, and why processors work hard to avoid them.
Recap
Recap and next step
- The control unit directs the processor, the ALU calculates, registers hold working values, the clock sets the pace, and three buses join the processor to memory.
- In the fetch stage, PC → MAR, memory → MDR, PC + 1, MDR → CIR; the instruction is then decoded and executed, with interrupts checked after each cycle.
- Von Neumann shares one memory and bus for instructions and data; Harvard separates them; modern processors combine the two.
- Time = cycles ÷ clock speed, but clock speed only compares fairly between similar designs, and faster clocks run hotter.
- Amdahl's law, S = 1 ÷ ((1 − p) + p ÷ n), means extra cores help less and less, with a limit of 1 ÷ (1 − p).
- Cache gives an average access time of t_c + (1 − h) t_m, so a small rise in hit rate gives a large saving.
Next chapter: Types of processor, input, output and storage covers pipelining, CISC and RISC processors, graphics processors, and the devices that store and move data.
For your exam board
OCR A Level Computer Science (H446): this chapter covers the structure and function of the processor, the registers, the fetch-decode-execute cycle, factors affecting performance, and von Neumann, Harvard and contemporary architectures in section 1.1.1, Structure and function of the processor, in Component 01, Computer systems.
AQA A Level Computer Science (7517): the processor and its components, the registers, the fetch-execute cycle, interrupts, factors affecting performance, and the stored-program concept appear in the fundamentals of computer organisation and architecture section, assessed on Paper 2.