On this page

Assembly isn’t about writing faster code than the compiler. It’s about seeing what the CPU actually pays for.

Whether you’re digging into unfamiliar C99 code, tracking down a bizarre crash in GDB, or investigating a sudden slowdown after a refactor, dropping down to the machine-instruction level pays off. That’s where you can see what data actually lives inside the CPU, how many trips the program makes to memory, and what the kernel is doing on your program’s behalf. This lesson is our starting point: I’ll compile a simple C99 function, inspect its actual assembly output, and dismantle two persistent myths about how CPUs work.

How to read the first section (lessons 00–02)
In this lesson and the next two (01 and 02), the main goal is getting familiar with the toolchain: the compiler, assembler, linker, and binary analysis utilities. Testing those tools on toy stubs makes no sense, so real instructions and directives (lea, xor, push rbp, syscall) show up in the examples right away. Don’t try to memorize their syntax yet—just watch what the tools report. A systematic breakdown of instructions starts in lesson 03.

Mental Model: A Line of C99 vs. What Happens on Silicon

What it looks like in C99 What happens in hardware
a + b is a single elementary operation The compiler picks an instruction, registers, and an addressing mode; the CPU decodes it, schedules it into the pipeline, and runs it on an execution unit
The CPU executes one instruction per clock cycle Instructions vary in latency and throughput; the pipeline overlaps independent ops, while data dependencies and cache misses cause stalls
Clock speed equals program speed Clock frequency sets cycle duration, but total runtime depends on instruction count, dependencies, caches, and memory traffic
Assembly is always faster than C Compilers often emit shorter, better-scheduled code; hand-written assembly helps in specific hotspots, not across the board

x86-64 is an ISA. The exact same machine code can run on different CPUs at different speeds: an ISA specifies the interface, not the underlying circuitry.

The term pipeline in the table refers to running stages in parallel inside a core. We’ll dig into pipeline costs and the difference between latency and throughput in lesson 20.

Mechanics: Clock Cycles, Execution Units, and Registers

A Clock Cycle Is Not an Instruction

Clock frequency ff sets the duration of a single cycle:

T=1f T = \frac{1}{f}
where
TT
duration of a single clock cycle, in seconds.
ff
clock frequency, in hertz.

Plugging f=3.8⋅109f = 3.8 \cdot 10^9 Hz into (1) gives:

T=13.8⋅109 Hz≈0.263⋅10−9 s≈0.26 ns T = \frac{1}{3.8 \cdot 10^9\text{ Hz}} \approx 0.263 \cdot 10^{-9}\text{ s} \approx 0.26\text{ ns}

So one clock cycle lasts roughly 0.26 ns. That doesn’t mean each instruction takes a single cycle: a CPU contains multiple execution units, and an ALU runs in parallel with load, store, and branch units.

Intermediate values don’t live in “source-code variables”—they live in registers. The compiler tries to keep hot values in registers, spilling them to memory only when necessary.

Our test machine shows the following memory hierarchy:

$ lscpu | grep -E '^(Architecture|Model name|CPU max MHz|L1d cache|L2 cache|L3 cache)'
Architecture:                            x86_64
Model name:                              AMD Ryzen 7 7840H with Radeon 780M Graphics
CPU max MHz:                             3801.0000
L1d cache:                               256 KiB (8 instances)
L2 cache:                                8 MiB (8 instances)
L3 cache:                                16 MiB (1 instance)

The (8 instances) note means each of the 8 cores has its own private cache: 256 KiB is the combined L1d total, meaning 32 KiB per core.

                 Core 0..7 (×8)                           Shared across die
┌─────────────┐   ┌───────────┐   ┌────────────┐   ┌────────────┐   ┌─────────────┐
│  Registers  │◄─►│ L1d 32KiB │◄─►│  L2 1 MiB  │◄─►│  L3 16MiB  │◄─►│     RAM     │
│ ~0–1 cycles │   │ ~4 cycles │   │ ~12 cycles │   │ ~40 cycles │   │ ~200 cycles │
└─────────────┘   └───────────┘   └────────────┘   └────────────┘   └─────────────┘

These rough latency numbers illustrate the gap: every cache miss costs an order of magnitude more than register arithmetic.

L1/L2/L3 caches aren’t “extra memory for convenience”—they exist to hide main memory latency. That’s why two programs with the exact same instruction count can have wildly different runtimes: one hits in cache, while the other stalls waiting on RAM.

A program can’t open a file or write to a terminal on its own—that’s the kernel’s job. Requests to the kernel are called system calls (we cover the kernel boundary in detail in lesson 12). That’s why an assembly program can print text without libc: it loads the arguments itself and asks the kernel to run write.

From C99 to Instructions

Execution units, registers, and caches explain what an operation costs, but everything starts with source code. Take a minimal function that adds two 32-bit integers, plus a main entry point to verify it:

sum_two.c
/* SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 */

#include <stdint.h>

int32_t sum_two(int32_t a, int32_t b)
{
    return a + b;
}

int main(void)
{
    return sum_two(20, 22) == 42 ? 0 : 1;
}

I’ll compile it with -O2 optimization and ask for Intel-syntax assembly output:

$ gcc -std=c99 -Wall -Wextra -Werror -pedantic -O2 \
    -S -masm=intel -fno-asynchronous-unwind-tables \
    -fno-stack-protector -o build/sum_two.s sum_two.c

The -fno-asynchronous-unwind-tables and -fno-stack-protector flags strip stack-unwinding metadata and stack-canary checks from the listing—we don’t need them just to read the function’s code.

The complete generated file looks like this:

sum_two.s
	.file	"sum_two.c"
	.intel_syntax noprefix
	.text
	.p2align 4
	.globl	"sum_two"
	.type	"sum_two", @function
"sum_two":
	lea	eax, [rdi+rsi]
	ret
	.size	"sum_two", .-"sum_two"
	.section	.text.startup,"ax",@progbits
	.p2align 4
	.globl	"main"
	.type	"main", @function
"main":
	xor	eax, eax
	ret
	.size	"main", .-"main"
	.ident	"GCC: (GNU) 16.2.1 20260810"
	.section	.note.GNU-stack,"",@progbits

The .p2align 4 directive advances the location counter to a 16-byte boundary (2⁴ = 16), padding the gap with nop instructions in code sections (and zeros in data sections): that’s GCC’s standard function-entry alignment (-falign-functions=16 under -O2), ensuring a function doesn’t start mid-way through an instruction-fetch block.

The .type "sum_two", @function and .size "sum_two", .-"sum_two" directives record the symbol’s type (“function”) and byte length in the symbol table. The linker, debugger, and profiler read this metadata, though it has no effect on the machine code itself.

In sum_two, only two instructions remain:

  • lea eax, [rdi+rsi] computes the sum into a separate destination register without touching CPU flags. A regular add overwrites its first operand, so without lea you’d need two instructions (mov and add);
  • the square brackets in lea don’t mean a memory read—it’s address-calculation syntax, so [rdi+rsi] simply reads as “the sum of rdi and rsi”;
  • address registers inside brackets in 64-bit mode are written as 64-bit (rdi, rsi) even when writing the result to 32-bit eax: this lets the compiler avoid an extra address-size override prefix, and writing to eax still uses only the lower 32 bits of the sum.

In C terms, you can think of lea as pointer arithmetic &((const char *)ptr)[idx] without the * dereference itself: char * gives a one-byte stride (scale = 1), whereas an int32_t * with the same index would jump by four bytes. The CPU computes the sum without ever touching RAM.

In practice, the two int32_t arguments arrive in edi and esi (the lower 32-bit halves of rdi and rsi), and the return value goes into eax. We’ll cover register layout and sub-register windows in detail in lesson 03.

Lines starting with a dot (.file, .text, .p2align, .globl) aren’t CPU instructions—they’re GNU Assembler directives controlling layout, alignment, and symbols. gcc -S emits them because at this stage the compiler outputs assembly text rather than raw machine bytes. The quotes around "sum_two" and "main" are how GCC 16 escapes symbol names in GAS Intel syntax so they can’t collide with instruction mnemonics.

main vanished as a computation altogether: the compiler folded 20 + 22 at compile time and replaced the entire check with xor eax, eax—return code 0.

xor eax, eax is the classic zeroing idiom:

  • any value XORed with itself evaluates to zero;
  • writing to eax automatically clears the upper 32 bits of rax—a rule called zero-extension (covered in detail in lesson 03).

This isn’t “assembly magic”—just standard compiler optimization, since the compiler is free to evaluate constants ahead of time.

To run the program and inspect its machine bytes, I’ll build an executable. Here gcc invokes the linker behind the scenes and implicitly links libc and CRT. Linking and CRT are covered in lesson 01 and lesson 02.

$ gcc -std=c99 -D_POSIX_C_SOURCE=200809L -Wall -Wextra -Werror -pedantic \
    -O2 -g -no-pie -o build/sum_two sum_two.c

The -no-pie flag disables PIE mode and locks addresses in place, making them easier to cross-reference in objdump and GDB.

Under the hood: why -no-pie fixes the 0x400000 base and what CRT does
  • By default, modern compilers build PIE binaries using instruction-pointer-relative addressing so the kernel can randomize their load addresses on every run. With -no-pie, the executable always starts at the traditional virtual address 0x400000 (the first 4 KiB hold headers, and code starts at 0x401000); more in lesson 01.
  • When building with gcc, startup CRT files are automatically linked in to call main and terminate the process after return. We’ll inspect their footprint in binary sections in lesson 02.

Here’s how we verify the binary’s behavior:

$ ./build/sum_two; echo $?
0

echo $? prints the exit status of the last command—whatever the process passed to exit; 0 means success.

The function’s machine code looks like this:

$ objdump -d -M intel --no-show-raw-insn build/sum_two | sed -n '/<sum_two>:/,/^$/p'
0000000000401130 <sum_two>:
  401130:	lea    eax,[rdi+rsi*1]
  401133:	ret

The --no-show-raw-insn flag hides raw machine bytes, leaving only addresses and mnemonics, while sed filters the output from the function label down to the next blank line; more on objdump in lesson 02.

Under the hood: why objdump prints rsi*1 rsi*1 is just rsi: objdump displays the index register’s scale factor explicitly, whereas NASM and GAS omit a multiplier of 1 in source code. It has zero impact on the result or instruction cost.

It compiles down to two instructions not because “the CPU computes so fast,” but because the compiler stripped away everything unnecessary. What the operation actually costs still depends on where rdi and rsi came from and what’s happening around them.

Checking in the Terminal: What Optimization Changes

Compare the same source compiled without optimization—we only need the sum_two snippet:

$ gcc -std=c99 -O0 -S -masm=intel -fno-asynchronous-unwind-tables \
    -fno-stack-protector -o /tmp/sum_two_O0.s sum_two.c
$ sed -n '/^"sum_two":/,/^[[:space:]]*\.size/p' /tmp/sum_two_O0.s
"sum_two":
	push	rbp
	mov	rbp, rsp
	mov	DWORD PTR -4[rbp], edi
	mov	DWORD PTR -8[rbp], esi
	mov	edx, DWORD PTR -4[rbp]
	mov	eax, DWORD PTR -8[rbp]
	add	eax, edx
	pop	rbp
	ret
	.size	"sum_two", .-"sum_two"

At -O0, we get a stack frame and intermediate memory stores. A stack frame is a scratch area on the stack where the compiler stores arguments and local values: push rbp and mov rbp, rsp set it up, and pop rbp tears it down. The stack itself is covered in lesson 09, and rbp-based frames in lesson 10. The operand DWORD PTR -4[rbp] accesses a DWORD-sized chunk of memory at address rbp - 4.

Under the hood: why GAS writes PTR and -4[rbp]
  • PTR only specifies operand size—it does not create a pointer;
  • in Intel syntax, GAS places the displacement outside the brackets, so -4[rbp] means [rbp - 4].

At -O2, those stores disappear. That brings us to an important practical rule: an assembly listing without optimization flags is almost useless. The exact same C99 code can show up as nine instructions or as two.

Common Pitfalls

  1. “Counting clock cycles by counting assembly lines.”
    Fact: sum_two has two instructions, yet you can’t claim it runs in two cycles: lea has latency, ret depends on the stack, and fetching the next instruction depends on the cache. lscpu shows three cache levels, not flat uniform memory.
    Cause: Confusing instruction count with execution time.
    Fix: Measure actual wall-clock or cycle counts (clock_gettime, perf stat—covered in lesson 08 and lesson 20) and inspect dependencies instead of line counts.

  2. “Assembly is always faster than C.”
    Fact: The compiler already emitted lea eax, [rdi+rsi]—three bytes and a single instruction. A hand-written mov + add version is longer and may perform no better.
    Cause: The optimizer understands instruction encoding, scheduling, and available ops.
    Fix: Write assembly surgically, compare the disassembly, and benchmark—don’t assume hand-written code wins by default.

  3. "-O0 and -O2 produce the same code, just faster."
    Fact: As shown above, the opposite is true: not only does speed change, but the instructions themselves and memory traffic change completely.
    Cause: Optimizations rewrite the program rather than merely speeding it up.
    Fix: Always record compiler flags alongside any listing, and never compare assembly outputs compiled with different flags.

  4. “A register is just a C variable.”
    Fact: In C99, a variable may live in memory, in a register, or disappear entirely after optimization. In assembly, a register is a physical storage slot that another instruction can immediately reuse.
    Cause: Mixing up levels of abstraction.
    Fix: Inspect concrete registers in GDB and don’t assume a variable’s name has to survive anywhere.

Lab

Goal. Compile your own C99 function with -O0 and -O2 and explain the difference in assembly output.

Contract. Write a function taking two integer arguments and returning a value, such as int32_t mix(int32_t a, int32_t b). Compile it twice with -std=c99 -Wall -Wextra -Werror -pedantic: first with -O0 -S -masm=intel, then with -O2 -S -masm=intel.

Verification criteria.

  1. Both listings compile without warnings.
  2. The -O2 version shows fewer memory accesses than -O0.
  3. You can name the registers used to pass arguments and return the result.
  4. objdump -d -M intel shows the same instructions as gcc -S.
Hints, expected output, and walkthrough

For int32_t mix(int32_t a, int32_t b) { return a * 3 + b; } on x86-64, GCC 16 with -O2 typically emits a compact sequence with lea and add, whereas -O0 emits a stack frame and memory stores. Exact output varies by GCC version and flags—always inspect your own compiler output.

Expected check:

text
$ gcc -std=c99 -Wall -Wextra -Werror -pedantic -O0 -S -masm=intel -o /tmp/mix_O0.s mix.c
$ gcc -std=c99 -Wall -Wextra -Werror -pedantic -O2 -S -masm=intel -o /tmp/mix_O2.s mix.c
$ grep -c 'PTR' /tmp/mix_O0.s /tmp/mix_O2.s

The -O0 file contains more PTR memory accesses because the compiler spills arguments into the stack frame. The -O2 file has fewer or none. Takeaway: -O0 makes debugging easier since values stay predictably in memory, but it tells you nothing about how the code behaves in release builds.

Lab source code, Makefile, and automated tests for this lesson: lessons/00-intro.

Summary

  1. Assembly is a tool for reading and debugging code, not a guaranteed speedup.
  2. Clock frequency sets cycle length, not instructions per second or total runtime.
  3. Compilers rewrite code: -O0 and -O2 generate different instructions, not the same program running faster.
  4. Registers, caches, and RAM are distinct tiers with vastly different access costs.
  5. Any assembly listing only makes sense alongside the compiler flags and toolchain version that produced it.
Next Up
The compiler emits an ELF file and machine instructions, though we haven’t unpacked what’s inside that file yet. In lesson 01, I’ll assemble a program using nasm and ld and break down object files, ELF executables, and four core build flags. In lesson 02, I’ll show how to inspect a compiled binary with six terminal utilities—from file to xxd.