Lessons in this course (11)

2. How the CPU executes instructions

Basic★ Must knowLesson 2 of 11

The CPU (central processing unit) runs a simple loop billions of times per second (clock speed, e.g. 3.5 GHz):

text
FETCH   next instruction from memory (address in the program counter)
DECODE  what it means (add, load, compare, jump …)
EXECUTE in the ALU (arithmetic/logic unit) or load/store unit
WRITE   result back to a register or memory → move to next instruction

Main parts:

PartRole
RegistersTiny, fastest storage inside the CPU (e.g. 16 general-purpose 64-bit registers on x64)
ALUDoes arithmetic and logic
Control unitDecodes instructions, controls the flow
Program counterAddress of the next instruction
Cache (L1/L2/L3)Fast copies of recently used memory
CoresIndependent execution units — a 8-core CPU runs 8 instruction streams at once (16 with hyper-threading/SMT)

What a line of C# becomes (simplified x64):

csharp
int total = price * qty + tax;
text
mov  eax, [price]      ; load from memory into register
imul eax, [qty]        ; multiply
add  eax, [tax]        ; add
mov  [total], eax      ; store back to memory

Speed tricks inside modern CPUs: pipelining (overlap stages of several instructions), out-of-order execution, branch prediction (guessing if results — sorted data makes branches predictable and loops faster), SIMD vector instructions (process 4–16 numbers at once — System.Numerics.Vector<T> in .NET).