COMPILER · BYTECODE · EVAL LOOP · OBJECTS · GIL · C EXTENSIONS · NUMPY · GPU · PYPY

How Python runs your code:
from bytecode to the GPU

Python is a language; the program that usually runs it is CPython, which compiles your code to bytecode and runs it in a loop written in C. Whether a script crawls or keeps a GPU busy depends on which parts of that program your code ends up in.

An online bookshop shows “readers who liked this also liked” on every book page. Each of its 100,000 books has an embedding, a list of 384 numbers, and two books are similar when the dot product of their lists is high. Every night a Python job finds the 10 most similar books for every book. The chapters run that job again and again: first as plain Python loops that would take 42.7 hours, then with C, NumPy and a GPU.

Here is everything between your script and the hardware. Most boxes won’t mean much yet; each chapter explains one of them.

MapThe solid box is one python3 process; the files above it are on disk, the hardware below. The column on the right holds the other programs that can run the same script.

You need to know how to write and run a Python script and install a package with pip; nothing about interpreters is assumed. The tutorial teaches CPython 3.15, NumPy 2.5.5 and PyTorch 2.15.0, checked against their source and documentation on 30 November 2026. The bookshop and every timing are illustrative; the sizes, names and defaults are real. For the same pipeline compared across Python, TypeScript, Java and Go, read Interpreted vs compiled. Tap any figure to open it full screen and zoom. Dotted terms are tappable.

CPython: the program that runs your script

Folio & Pine’s nightly job is a file, similar.py, and every night a scheduler runs python3 similar.py. The file is text, and a CPU can’t run text. Something reads it and does what it says, and that something is a program like any other, with its own process, its own memory and its own speed. When you type python3 similar.py, what actually runs?

STEP 01 / 04

THE MAP SO FAR

Fig 1.1The accent box is one python3 process; faint parts arrive in later chapters.

python3 similar.py starts one operating-system process, and everything this tutorial covers happens inside that box or in the hardware under it. The program in the box is CPython, written in C. It is the same program whether it came from python.org, Homebrew, your Linux distribution or uv.

CPython reads your script and makes the CPU do what it says, which the map draws as one arrow from the process to the CPU cores. Each faint part inside the box is a piece of CPython that a later chapter opens up. The column on the right holds other programs that can replace the whole box.

STEP 02 / 04

PYTHON IS A LANGUAGE, AND CPYTHON IS ONE PROGRAM THAT RUNS IT

Fig 1.2The accent box is the implementation you run by default; the faint ones run the same language.

Python the language is defined by documents: the Python Language Reference and the standard library documentation. CPython is its reference implementation, the program that settles what those documents leave open, and the one almost everyone runs. The packages you install with pip, and their compiled parts, are built for it.

Other programs implement the same language: PyPy, GraalPy, MicroPython and Pyodide each run Python code in their own way, and chapter 10 compares them. To find out which one you are running, ask it. sys.implementation.name is 'cpython' under CPython, and sys.version_info gives the version, here 3.15.2.

WHICH PYTHON IS THIS? ASK THE INTERPRETER
$ python3 -c "import sys; print(sys.implementation.name)"
cpython
$ python3 -c "import sys; print(sys.version_info[:3])"
(3, 15, 2)
$ python3 -c "import sys; print(sys.executable)"   # which file on disk is running
STEP 03 / 04

THE PROCESS RUNS CODE BEFORE YOURS

Fig 1.3Follow 1 to 5: your first line runs at step 5.

Before the first line of similar.py runs, CPython starts itself. It sets up the interpreter, its built-in types and the sys module. It imports its core modules, which since 3.11 are frozen into the executable, so no file is read for them. Then it runs the standard site module, which adds site-packages, the folder pip installs into, to sys.path.

Only then does CPython compile similar.py and run it as the module named __main__. Each import statement in it runs that module’s top level once, so a heavy import costs time before your own code does anything. python3 -X importtime similar.py prints every module imported and how long each took.

STEP 04 / 04

PYTHON IS COMPILED, THEN INTERPRETED

Fig 1.4The CPU at the bottom never sees your code; it runs the loop that reads it.

CPython runs a file in two stages inside one process. First its compiler turns the file into bytecode: compact instructions for CPython itself, not for the CPU. Then its evaluation loop, a function written in C, runs that bytecode one instruction at a time. So the answer to “interpreted or compiled?” is both, one after the other.

The CPU only ever runs CPython’s own machine code, made when CPython itself was built. By default no machine code is made for your script, and no executable of it exists anywhere. For how V8, the Java virtual machine and Go make the same choice, read Interpreted vs compiled.

COMMON QUESTIONS

Is python3 on my laptop the same program as on the server?
Usually both are CPython, but often different versions built by different compilers. python3 -VV prints both, so compare that line first when code works on one machine and fails on the other.
Is a virtual environment a different Python?
No. It is a folder with its own site-packages and a link to an existing python3, and its pyvenv.cfg file records which one. Activating it puts the folder’s bin directory first on your PATH.
Can I ship a Python program as one executable?
Tools such as PyInstaller bundle CPython, your code’s bytecode and its libraries into one file. CPython still runs inside that file, interpreting the same bytecode as before.

WHAT YOU NOW KNOW

  • python3 similar.py starts CPython, a program written in C, in one process; the script is its input.
  • Before your first line runs, CPython sets up its runtime, imports its frozen core modules and lets site set sys.path.
  • CPython compiles each file to bytecode, then interprets that bytecode: compiled and interpreted, one after the other.
DEEP DIVE: who decides what Python means · release cadence · startup cost · embedding CPython · which python3 you ran

Who decides what Python means

The language is defined by the Language Reference and changed through PEPs, Python Enhancement Proposals, which the steering council accepts or rejects. Where the reference leaves room, the docs mark CPython’s behaviour as a “CPython implementation detail”: exactly when an object is freed, or id() returning a memory address. Other implementations may behave differently there.

Release cadence

PEP 602 sets one feature release a year, each October, with about five years of bug fixes and then security fixes. 3.15.0 came out on 9 October 2026, and 3.15.2 is the release this tutorial teaches. Bytecode and the C internals change between feature releases; the language mostly grows.

Startup cost

Since 3.11 the modules CPython needs at startup are frozen into the executable. 3.13 stopped “deep-freezing” them into ready-made objects, but they are still frozen. -X importtime prints one line per import with its own and its cumulative time, and -X importtime=2 (3.14) also lists modules that were already imported.

-S skips site, and -I isolates a run from your environment variables, the script’s folder and your user site-packages. 3.15 adds lazy import (PEP 810), which binds the name at once but loads the module only when the name is first used.

Embedding CPython

CPython is also a library, libpython, that other programs link and start with Py_Initialize(). Blender, for example, runs its add-ons and scripting console on an embedded CPython. The same compiler and evaluation loop then run inside the host program’s process.

Which python3 you ran

sys.executable prints the path of the running interpreter, and which -a python3 lists every python3 on your PATH in the order the shell tries them. Inside a virtual environment, python3 is a link back to a base interpreter. uv downloads and manages its own CPython builds, so a uv project may run a different python3 from the one your shell finds.

The compiler and the .pyc cache: source becomes bytecode

CPython is running and has found similar.py. Before the first line can run, the text has to become something the evaluation loop can step through. catalog.py, which the script imports, has to be found on disk and turned into the same thing. Doing that on every start would waste time on files that never change. What does Python do with your file before the first line runs, and what does it keep for next time?

STEP 01 / 04

THE MAP SO FAR

Fig 2.1The accent parts turn files into bytecode and keep it for the next run.

Three parts are new. The compiler turns source text into bytecode. The import system finds a module such as catalog on sys.path and decides whether it needs compiling. __pycache__/, a folder beside each imported module, holds the compiled result so the next start can skip that work.

similar.py goes straight to the compiler. catalog.py goes through the import system first, which reads and writes __pycache__ and hands the compiler only what needs compiling. Whatever the compiler makes goes down to the evaluation loop.

STEP 02 / 04

THE COMPILER TURNS TEXT INTO A CODE OBJECT

Fig 2.2Follow the inner line from text at 1 to bytecode at 4; each stage names its source file.

The compiler is C code inside the process, and it works in stages. The tokenizer splits the text into names and operators. The parser builds an AST, an abstract syntax tree: total += query[i] * book[i] becomes an AugAssign whose value is a multiply of two subscripts. The symbol table then decides, once per function, which names are local and which are global.

Code generation turns the tree into instructions, an optimiser tidies them, and an assembler packs the result into a code object. The inner line comes out as 8 instructions. The optimiser also does small jobs ahead of time: 2 * 3 in your source is stored as 6.

THE INNER LINE’S TREE, AS THE AST MODULE PRINTS IT
import ast

tree = ast.parse("total += query[i] * book[i]")
print(ast.dump(tree.body[0], indent=2))
# AugAssign(
#   target=Name(id='total', ctx=Store()),
#   op=Add(),
#   value=BinOp(
#     left=Subscript(
#       value=Name(id='query'),
#       slice=Name(id='i')),
#     op=Mult(),
#     right=Subscript(
#       value=Name(id='book'),
#       slice=Name(id='i'))))
STEP 03 / 04

A CODE OBJECT HOLDS THE BYTECODE AND THE NAMES IT USES

Fig 2.3The accent row becomes numbered slots; the names in the row below it stay names, looked up as the code runs.

Every function gets its own code object, score.__code__, nested inside the module’s. co_varnames lists the locals, ('query', 'book', 'total', 'i'), and the bytecode refers to each by position: slot 0 for query up to slot 3 for i. co_names lists the globals it uses, range and len, and those stay names.

co_consts holds constants such as 0.0, and co_code holds the bytecode itself. The split between slots and names matters at run time: reading a local is an index into the call’s slots, while a global has to be looked up by name, first in the module’s globals and then in the built-ins.

SCORE’S CODE OBJECT, FIELD BY FIELD
code = score.__code__
print(code.co_varnames)   # ('query', 'book', 'total', 'i'): slots 0 to 3
print(code.co_argcount)   # 2: the first two slots are the arguments
print(code.co_names)      # ('range', 'len'): looked up by name at run time
print(code.co_consts)     # the constants, 0.0 among them
STEP 04 / 04

IMPORTED MODULES ARE COMPILED ONCE AND CACHED

Fig 2.4The accent slice is the magic number: a different Python version reads it and compiles again.

For import catalog, the import system searches each folder on sys.path, finds catalog.py and looks for __pycache__/catalog.cpython-315.pyc, a .pyc file. If the modification time and size recorded in its header match catalog.py, it loads the code object and skips the compiler. Otherwise it compiles the source and writes a fresh file.

The header is 16 bytes: the magic number, 3666 for CPython 3.15, so any other version ignores the file, then flags, the source’s modification time and its size. The script you name on the command line gets none of this: similar.py is compiled on every run and never cached.

THE CACHE ON DISK, AND HOW TO FILL IT OR TURN IT OFF
$ python3 similar.py                 # imports catalog, so catalog gets a .pyc
$ ls __pycache__
catalog.cpython-315.pyc
$ python3 -m compileall -q .         # compile every module ahead of time, e.g. in a Docker build
$ PYTHONDONTWRITEBYTECODE=1 python3 similar.py   # compile in memory, write no .pyc

COMMON QUESTIONS

Is a .pyc faster to run than a .py?
No. Only loading is faster, because the compile is skipped. The bytecode is the same, so the run takes as long.
Does shipping only .pyc files hide my source?
Barely. Bytecode decompiles into readable Python, and a .pyc loads only on the Python version that wrote it.
Should __pycache__ go into git?
No. Python rebuilds it on demand, and its files differ for every Python version. Add it to .gitignore.

WHAT YOU NOW KNOW

  • The compiler turns score into a code object: four local slots, two global names, and bytecode for every line.
  • import catalog reuses catalog.cpython-315.pyc while the modification time and size in its header still match catalog.py.
  • similar.py itself is compiled on every run and never cached, so keep the script small and the work in modules.
DEEP DIVE: the parser and the ast module · constant folding · hash-based .pyc files · how import finds a module · lazy imports

The parser and the ast module

Since 3.9 (PEP 617) CPython’s parser is generated from a grammar file, Grammar/python.gram, and it can look ahead as far as a rule needs. That freedom is what made room for match statements and parenthesised with blocks. Since 3.10 its errors name the likely cause, such as a bracket that was never closed.

ast.parse() returns the same tree the compiler sees, and ast.dump() prints it. Linters, formatters and tools that rewrite code read that tree rather than the text.

Constant folding

The optimiser works on a control-flow graph of the instructions, in Python/flowgraph.c. It folds constant expressions, so 2 * 3 is stored as 6, and removes code that can never run, such as lines after a return. python3 -O also drops assert statements and if __debug__: blocks, and caches the result in a separate .opt-1.pyc.

Hash-based .pyc files

PEP 552 added a second kind of .pyc that records a hash of the source instead of its time and size. A checked one is compared with the source on every import; an unchecked one is trusted as it is. When SOURCE_DATE_EPOCH is set, py_compile writes checked hash-based files by default, so two builds of the same source produce identical bytes.

sys.pycache_prefix (3.8) moves every cache file into one separate tree, and -B or PYTHONDONTWRITEBYTECODE stops Python writing them at all.

How import finds a module

import catalog first checks sys.modules. A module imported before is returned at once, so a second import is nearly free. Otherwise each finder on sys.meta_path is asked in turn: BuiltinImporter for modules compiled into python3, FrozenImporter for frozen ones, and PathFinder, which walks sys.path.

PathFinder picks a loader for what it finds: SourceFileLoader for a .py file, SourcelessFileLoader for a .pyc with no source beside it, and ExtensionFileLoader for a compiled .so library.

Lazy imports

CPython 3.15 adds lazy import json (PEP 810). The name is bound at once, but the module loads only when the name is first used, which shortens the startup that -X importtime measures. lazy is a soft keyword, so code that uses it as a variable name keeps working, and the -X lazy_imports option controls the feature for a whole run.

ERRORS THIS CHAPTER EXPLAINS

ImportError: bad magic number in 'catalog'
a .pyc written by another Python version, loaded without its .py beside it
ship catalog.py, or compile the .pyc again with this Python
ModuleNotFoundError: No module named 'catalog'
the folder holding catalog.py isn’t on sys.path: the wrong working directory or virtual environment
run from the project root, or install the project into the environment

The evaluation loop: one instruction at a time

score is now a code object full of bytecode, and bytecode still isn’t something the CPU can run. CPython runs it itself, with one C function that reads an instruction, does what it says and moves to the next. That function is where almost every second of the pure-Python job is spent. How does bytecode run, and what does one line of Python cost?

STEP 01 / 04

THE MAP SO FAR

Fig 3.1The accent box runs every instruction of every Python function.

The evaluation loop is one C function, _PyEval_EvalFrameDefault, in CPython’s Python/ceval.c. Every Python function you call runs inside it: your own, the ones in catalog, and the parts of the standard library written in Python.

Each call gets a frame: a record holding the call’s local slots, a small stack of values in use and a pointer to the next instruction. The loop works on one frame at a time. When score returns, its frame is dropped and the caller’s frame carries on.

STEP 02 / 04

THE LOOP READS AN INSTRUCTION, RUNS ITS C CODE, MOVES ON

Fig 3.2Follow 1 to 4 once for every instruction your code runs.

Each instruction is two bytes, an opcode and its argument, and some are followed by a few cache entries. The loop fetches the instruction the frame points at, jumps to the C code for that opcode and runs it. Most of that code pops values off the frame’s value stack and pushes a result: BINARY_OP (*) pops two values and pushes their product.

The C for each instruction is written once, in Python/bytecodes.c, and the build generates the loop’s cases from it into generated_cases.c.h. Frames live on a stack of their own, one per thread, so a call costs little: push a frame, run, pop it. Interpreted vs compiled shows the same kind of loop in other runtimes.

STEP 03 / 04

THE INNER LINE IS 8 INSTRUCTIONS

Fig 3.3The accent row is the multiply; every other row moves values on or off the stack.

dis, the standard library’s disassembler, prints the bytecode: dis.dis(score). The inner line is 8 instructions. Two paired loads push total and query, one more pushes i, and BINARY_OP ([]) replaces query and i with query[i]. The same happens for book[i]. Then BINARY_OP (*) multiplies, BINARY_OP (+=) adds, and STORE_FAST total saves the result.

Around the line, the loop adds three more: FOR_ITER takes the next i from the range, STORE_FAST i stores it and JUMP_BACKWARD goes back to the top. That makes 11 instructions for every multiply-add, and only one of them multiplies. The listing is for CPython 3.15; instruction names change between versions.

DIS.DIS(SCORE): THE LOOP, NAMES AND ARGUMENTS ONLY
# dis.dis(score) on CPython 3.15, the loop only:
# names and arguments; offsets and line numbers left out
L1: FOR_ITER                            (to L2)
    STORE_FAST                          (i)
    LOAD_FAST_BORROW_LOAD_FAST_BORROW   (total, query)
    LOAD_FAST_BORROW                    (i)
    BINARY_OP                           ([])
    LOAD_FAST_BORROW_LOAD_FAST_BORROW   (book, i)
    BINARY_OP                           ([])
    BINARY_OP                           (*)
    BINARY_OP                           (+=)
    STORE_FAST                          (total)
    JUMP_BACKWARD                       (to L1)
L2: END_FOR
STEP 04 / 04

ONE QUERY RUNS 422.4 MILLION INSTRUCTIONS

Fig 3.4The accent line is one query’s count: 11 instructions for each of 38.4 million multiply-adds.

One query scores one book against all 100,000: 100,000 books × 384 numbers is 38,400,000 multiply-adds, each paying for 11 instructions. That is 422.4 million instructions per query. At an illustrative 40 ns per multiply-add, a query takes 1.5 s, about 3.6 ns per instruction, and each instruction is many machine instructions.

The night runs one query per book, 100,000 of them, so the pure-Python job takes 42.7 hours (illustrative). A loop compiled to machine code would do each multiply-add in a few machine instructions; here each one is 11 trips through the evaluation loop.

THE PURE-PYTHON JOB: SCORE() AND THE NIGHT LOOP
from catalog import load_embeddings


def score(query, book):
    total = 0.0
    for i in range(len(query)):
        total += query[i] * book[i]
    return total


books = load_embeddings()            # 100,000 lists of 384 floats
similar = {}
for n, query in enumerate(books):    # one query per book: 100,000 of them
    scores = [score(query, book) for book in books]
    best = sorted(range(len(books)), key=scores.__getitem__, reverse=True)
    similar[n] = best[1:11]           # the 10 best, without the book itself

COMMON QUESTIONS

Can I see the bytecode of my own code?
Yes. python3 -m dis file.py prints a whole file, and dis.dis(func) prints one function in a session.
Is bytecode the same across Python versions?
No. Instructions change in most releases, which is why the .pyc name carries cpython-315 and a .pyc never loads on another version.
Does -O make code faster?
Barely. It removes assert statements and if __debug__: blocks, nothing else; the evaluation loop runs the rest the same way.

WHAT YOU NOW KNOW

  • The evaluation loop fetches each two-byte instruction, runs its C code and moves on; a frame holds the locals and the value stack.
  • The inner line of score is 8 instructions, and the whole loop body is 11.
  • One query runs 422.4 million instructions, so the pure-Python night takes 42.7 hours (illustrative).
DEEP DIVE: computed gotos and tail calls · how instructions are defined · frames on a per-thread stack · why locals are fast · tracing and sys.monitoring

Computed gotos and tail calls

A plain C switch sends every instruction through one shared jump, which the CPU predicts badly. Built with GCC or Clang, CPython uses computed gotos instead: each instruction’s code ends with its own jump to the next one, so the CPU’s branch predictor sees one branch per opcode.

3.14 added a tail-calling interpreter, in which each instruction is a small C function that calls the next as its last act. Built with Clang 19 or newer it ran 3–5% faster. In 3.15 it also builds with Microsoft’s compiler, MSVC, and the official Windows x64 binaries use it, which the release notes put at 15–20% faster on average.

How instructions are defined

Python/bytecodes.c describes every instruction in a small language of its own: its name, the stack values it takes and leaves, its cache entries and its C body. A generator turns that file into generated_cases.c.h, the cases the loop includes, and into the tables dis reads. Since 3.11 some instructions are followed by inline cache entries, extra code units the loop skips and fills in as the code runs.

Frames on a per-thread stack

Since 3.11 a frame is a plain C struct, _PyInterpreterFrame, kept on a per-thread stack of frames rather than allocated as a Python object. A full frame object is made only when something asks for one: sys._getframe(), a traceback, or a debugger. That is one reason calls got cheaper in 3.11.

Why locals are fast

LOAD_FAST and LOAD_FAST_BORROW read a numbered slot of the frame: one array index. LOAD_GLOBAL looks a name up in the module’s globals and then in the built-ins. At module level the compiler emits LOAD_NAME, a dictionary lookup for every variable, which is why the same loop runs slower outside a function.

Tracing and sys.monitoring

sys.settrace calls a Python function for every line, which slows the whole program while a debugger or coverage tool is attached. sys.monitoring (PEP 669, 3.12) lets a tool subscribe only to the events it needs, per code object, and switch them off again, so debuggers and coverage cost much less. Recent versions of coverage.py can use it.

Objects: why a float takes 24 bytes

Chapter 03 counted 11 instructions for every multiply-add, and the multiply instruction does more than multiply. In Python every value, even a single float, is an object somewhere in memory, and every instruction works with references to objects, never with raw numbers. That choice lets a list hold anything and a function take any type, and it is also most of why the loop is slow. What is a Python number in memory, and who frees it when you’re done?

STEP 01 / 04

THE MAP SO FAR

Fig 4.1The accent box holds every value your code creates.

Every value the evaluation loop touches lives in the process’s memory as an object: each float in a book’s embedding, the list that holds them, even the function score itself. In CPython’s C source each one starts with the same struct, a PyObject: a count of the references to it and a pointer to its type.

The loop never holds a raw number. A local slot, a list element and an entry on the value stack each hold a pointer to an object, 8 bytes on a 64-bit machine. The arrow from the loop down to the objects box is that traffic: almost every instruction reads an object, makes one or drops one.

STEP 02 / 04

A FLOAT IS A 24-BYTE OBJECT, AND A LIST HOLDS POINTERS

Fig 4.2The accent float is what one list slot points to; the strip below holds the same numbers unboxed.

sys.getsizeof(1.0) is 24 bytes: 8 for the reference count, 8 for the type pointer and 8 for the double itself. Keeping a raw value inside a heap object like this is boxing. An int takes 28 bytes. Ints from -5 to 1024 are made once at start-up and shared, so n = 7 allocates nothing.

A book’s embedding as a list is a 56-byte list object, 384 pointers of 8 bytes and 384 floats of 24 bytes: 12,344 bytes for numbers that fit in 1,536 bytes as raw float32. Across 100,000 books the catalogue takes about 1.23 GB, against 153.6 MB raw.

WHAT SYS.GETSIZEOF REPORTS ON CPYTHON 3.15
import sys

sys.getsizeof(1.0)           # 24: reference count, type pointer, the double
sys.getsizeof(1)             # 28
sys.getsizeof([0.0] * 384)   # 3128: the list and its 384 pointers, not the floats
# one book as a list: 12,344 bytes; as float32 in an array: 1,536
STEP 03 / 04

ONE MULTIPLY CHECKS TYPES AND ALLOCATES A NEW OBJECT

Fig 4.3Only the accent step multiplies; the other six exist because values are objects.

BINARY_OP (*) receives two pointers, not two numbers. Python has dynamic typing: the type belongs to the value, not to the variable, so the same instruction must work whether query[i] holds a float, an int or a string. It reads each object’s type pointer and asks that type for its multiply.

For two floats that takes seven steps. Pop the two references, look up the types, read the two doubles out of their objects, multiply, allocate a new 24-byte float for the product, drop one reference to each operand, and push the result. Only step 4 is arithmetic, and the += on the same line does all seven again. A C loop over raw doubles does step 4 alone.

STEP 04 / 04

A COUNT OF REFERENCES FREES MOST OBJECTS AT ONCE

Fig 4.4Follow the accent count: it reaches zero and the float is freed on the spot.

Every object carries a reference count: how many slots, lists and stack entries point at it. A new reference adds one and a dropped one subtracts one. When the count reaches zero, CPython frees the object on the spot. The product of query[i] * book[i] lives for one instruction: the multiply makes it, and the add uses it and drops it.

Counts can’t free a cycle. Two objects that refer to each other keep both counts above zero after your code lets go of them. For those, CPython runs a cycle collector now and then. It only tracks containers such as lists, dicts and instances, never floats. In 3.15 it is generational, and gc.get_threshold() returns (2000, 10, 10).

ONE REFERENCE AT A TIME, THEN A CYCLE ONLY GC.COLLECT() FREES
import gc

price = sum([7.5, 7.5])   # 15.0, a float made at run time; one reference: price
alias = price             # two references, one object
del alias                 # back to one; the object stays
del price                 # zero: CPython frees the float at once

a, b = [], []
a.append(b)
b.append(a)          # a cycle: each list holds a reference to the other
del a, b             # each count stays at 1, so neither is freed yet
gc.collect()         # the cycle collector finds both lists and frees them

COMMON QUESTIONS

Why can a is b be True for small ints and False for large ones?
Ints from -5 to 1024 are shared objects in 3.15, so equal small ints are the same object. Larger ints computed at run time are separate objects. Compare numbers with ==, never is.
Can I turn the cycle collector off?
gc.disable() stops only the cycle collector; reference counts keep freeing everything else. Some servers call gc.freeze() after start-up instead, so the collector stops scanning objects that live for the whole process.
Does del x free the object?
It removes one reference, the name x. The object is freed when its count reaches zero, which is at once only if nothing else, such as a list or another name, still points at it.

WHAT YOU NOW KNOW

  • A float is a 24-byte object, so the catalogue as lists takes about 1.23 GB against 153.6 MB of raw float32.
  • Each multiply looks up types, unboxes both values, multiplies, allocates a new float and adjusts reference counts.
  • Reference counts free most objects the moment the last reference goes; a generational cycle collector frees the cycles.
DEEP DIVE: the object header · pymalloc and free lists · immortal objects · the cycle collector · __slots__

The object header

Every object starts with ob_refcnt and ob_type, 16 bytes on a 64-bit build. Containers that can form cycles, such as lists, carry a second header in front of that for the cycle collector, which is part of why an empty list reports 56 bytes.

The free-threaded build of chapter 06 has a 32-byte header: an owning thread id, flags, a small mutex, collector bits, a local and a shared reference count, and the type pointer. A float takes 40 bytes there.

pymalloc and free lists

Small objects don’t come from the C library’s malloc one by one. CPython’s own allocator, pymalloc, carves them out of large arenas it requests from the operating system, which makes the many small allocations of a loop cheap. Freed floats go onto a free list first, and the next new float reuses one of them.

PYTHONMALLOC=malloc switches to the system allocator, which memory debuggers need. The free-threaded build uses mimalloc instead of pymalloc.

Immortal objects

None, True, False and the small ints are immortal since Python 3.12: their reference count is a fixed, very large value that increments and decrements never change. That is why sys.getrefcount(None) prints a huge constant. Immortal objects are never freed, and threads can share them without touching a count.

The cycle collector

It sorts tracked objects into three generations, with thresholds (2000, 10, 10). The youngest is collected once new tracked objects outnumber freed ones by the first threshold; survivors move to an older generation that is scanned less often. Servers that fork workers call gc.freeze() first, so the collector doesn’t touch, and copy, pages the workers share.

Python 3.14.0 shipped an incremental collector. It was reverted in 3.14.5 and left out of 3.15 because of “significant memory pressure in production”, so 3.15 is back to the generational one.

__slots__

An ordinary instance keeps its attributes in a dict. A class that declares __slots__ = ('title', 'price') stores them in fixed slots instead and gets no per-instance dict. That saves memory when a program holds millions of small objects, and it changes nothing for code that holds a few.

The specializing interpreter and the JIT: CPython speeds up its own loop

Chapter 04 showed what one generic multiply does: look up the types, unbox, multiply, box the result. In this job the types never change; query[i] is a float every one of the 38.4 million times. CPython uses that in two ways: it rewrites instructions for the types they keep seeing, and, in builds that include it, it can compile hot loops to machine code. How does CPython make a hot loop cheaper without changing your code, and why is it still slow?

STEP 01 / 04

THE MAP SO FAR

Fig 5.1The accent chip rewrites instructions; the accent box beside the loop compiles hot code.

Two parts are new, and both work on the evaluation loop’s bytecode. The specializer is part of the loop itself since CPython 3.11: it rewrites instructions while they run, for the types they keep seeing. It has no switch and needs no flag.

The JIT sits beside the loop and turns the hottest loops into machine code while the program runs. In 3.15 it is still experimental and off by default, and only some builds of CPython include it at all.

STEP 02 / 04

HOT INSTRUCTIONS REWRITE THEMSELVES FOR THE TYPES THEY SEE

Fig 5.2The accent rows changed on their second execution; the faint ones had nothing to specialize.

This is specialization. An instruction runs its generic version once. On execution 2 it looks at the types it got and rewrites itself in the bytecode: BINARY_OP (*) on two floats becomes BINARY_OP_MULTIPLY_FLOAT, and a subscript of a list by an int becomes BINARY_OP_SUBSCR_LIST_INT.

In score(), 6 of the 11 instructions change; the plain loads and stores have nothing to specialize. Each specialized instruction starts with a guard, a cheap check that its operands still have the types it saw. When a guard fails, the generic code runs, and the instruction tries again later. Python 3.11’s release notes measured 1.25× faster on average than 3.10.

DIS.DIS(SCORE, ADAPTIVE=TRUE): THE LOOP AFTER IT HAS RUN
# dis.dis(score, adaptive=True) after two calls, the loop only
L1: FOR_ITER_RANGE                      (to L2)
    STORE_FAST                          (i)
    LOAD_FAST_BORROW_LOAD_FAST_BORROW   (total, query)
    LOAD_FAST_BORROW                    (i)
    BINARY_OP_SUBSCR_LIST_INT           ([])
    LOAD_FAST_BORROW_LOAD_FAST_BORROW   (book, i)
    BINARY_OP_SUBSCR_LIST_INT           ([])
    BINARY_OP_MULTIPLY_FLOAT            (*)
    BINARY_OP_ADD_FLOAT                 (+=)
    STORE_FAST                          (total)
    JUMP_BACKWARD_NO_JIT                (to L1)
STEP 03 / 04

THE SPECIALIZED LOOP STILL BOXES EVERY FLOAT

Fig 5.3The accent step is still there after specialization: a new object for every product.

BINARY_OP_MULTIPLY_FLOAT drops one of chapter 04’s seven steps: it no longer asks the type for its multiply, because the guard has already checked that both operands are floats. The other six stay. It still pops two references, reads two doubles, allocates a new 24-byte float for the product, drops two references and pushes one.

The loop body is still 11 instructions, 38.4 million times per query. Chapter 03’s 1.5 s per query (illustrative) already includes specialization: it is how fast this loop runs on CPython 3.15. Getting rid of the boxes needs a compiler that keeps the doubles in CPU registers instead of in objects.

STEP 04 / 04

THE JIT COMPILES HOT TRACES, AND IT IS OFF BY DEFAULT

Fig 5.4Follow 1 to 4; the chip says why most runs never reach step 4.

When a loop’s backward jump has run 4000 times, CPython records the loop as a trace: its instructions split into smaller micro-ops, along the path the code actually took. The JIT builds machine code by copy-and-patch: it copies templates that LLVM compiled when CPython itself was built, and fills in addresses and constants. The next lap jumps to that code.

In 3.15 the trace can update a temporary float in place and skip some reference-count updates, but values are still objects. The published average gains are 7–8% on x86-64 Linux and 11–12% on macOS on Apple silicon; single benchmarks range from slower to more than twice as fast.

The JIT is off by default. PYTHON_JIT=1 turns it on at start-up in builds that include it. Interpreted vs compiled shows the same idea in V8 and the JVM, where it is on for every program.

IS THE JIT BUILT IN, AND IS IT ON?
$ python3 -c "import sys; print(sys._jit.is_available())"   # was this build compiled with the JIT?
$ PYTHON_JIT=1 python3 -c "import sys; print(sys._jit.is_enabled())"
$ PYTHON_JIT=1 python3 similar.py    # the same job with the JIT on

COMMON QUESTIONS

Do I have to do anything to get specialization?
No. It has been on since Python 3.11 and needs no flag and no change to your code.
Will the JIT make Python as fast as Java?
Not soon. Its traces still work on Python objects, even where 3.15 can update a float in place, and its average gain in 3.15 is 11–12% at best.
What breaks specialization?
Types that keep changing at one spot. An add that sees ints on some laps and floats on others keeps failing its guard and runs the generic instruction.

WHAT YOU NOW KNOW

  • From execution 2 on, the multiply runs as BINARY_OP_MULTIPLY_FLOAT behind a cheap type check.
  • Specialized or not, every product is a new 24-byte object, and the loop body stays 11 instructions.
  • The 3.15 JIT is experimental and off by default, and averages 7–8% faster on Linux and 11–12% on macOS.
DEEP DIVE: inline caches and counters · micro-ops and the optimizer · copy-and-patch · why CPython can’t unbox yet · the Faster CPython project

Inline caches and counters

Since 3.11 many instructions are followed by cache entries in the bytecode itself: a 16-bit counter and room for what the specialized form needs, such as a type version or a dict index.

The counter starts low enough that an instruction specializes on execution 2. After a miss it backs off and waits longer before it tries again, so an instruction whose types really do vary stops paying for attempts that keep failing.

Micro-ops and the optimizer

The specialized bytecode is tier 1. A JIT trace is tier 2: the hot path as micro-ops, each a small piece of one instruction, such as a guard or the multiply itself. 3.15 added a tracing front end that records the path the code really took, branches included, instead of guessing it from the bytecode.

Before compiling, an optimizer works on the trace. It follows types and constants along it, removes guards it can prove will pass, and in 3.15 tracks objects that have a single reference, so a temporary float can be updated in place.

Copy-and-patch

When CPython is built with the JIT, LLVM 21 compiles a template, called a stencil, for every micro-op. Each stencil is machine code with holes for values only known at run time: an address, a constant, the next stencil. At run time the JIT copies the stencils for a trace one after another and patches the holes, which takes far less time than running a compiler.

LLVM is needed only to build CPython, never to run it. The build flag is --enable-experimental-jit, where yes-off compiles the JIT in but leaves it off until PYTHON_JIT=1.

Why CPython can’t unbox yet

Compiled extensions (chapter 07) receive pointers to objects and change reference counts themselves. Any value such code might see has to exist as a real object with a correct count, so CPython can keep a double raw only where it can prove no C code will look. PyPy (chapter 10) makes no such promise to C code, and its traces keep floats as raw numbers.

The Faster CPython project

Mark Shannon’s plan set out to make CPython faster by “a factor of (approximately) five” in four stages. A team funded by Microsoft delivered the specializing interpreter of 3.11, 1.25× faster on average, and the first JIT. Microsoft ended that funding on 15 May 2025; the work continues with other contributors.

The GIL: one thread runs Python at a time

The machine running the job has many cores, and the obvious fix for a slow loop is to split the 100,000 books into 4 parts and score them in 4 threads. Try it, and each query takes as long as before. Inside one CPython process a lock decides which thread may run bytecode, and only one thread can hold it. Why don’t 4 threads make the job 4 times faster, and what does?

STEP 01 / 04

THE MAP SO FAR

Fig 6.1The accent lock sits between every thread and the evaluation loop.

The GIL, the global interpreter lock, belongs to the interpreter, and every thread in the process shares it. A thread must hold it to run bytecode or touch an object. It sits beside the evaluation loop on the map because the loop checks, at backward jumps and calls, whether another thread is waiting for it.

One lock is how CPython keeps reference counts and its own state correct without a lock on every object. Chapter 04’s counts change on almost every instruction; while only one thread runs at a time, a plain add to a count is safe.

STEP 02 / 04

4 THREADS TAKE TURNS ON ONE LOCK

Fig 6.2Only one lane is accent at any moment: that thread holds the GIL.

The code below gives each of 4 threads 25,000 books to score against one query. All of them run Python bytecode, so all of them need the GIL. One holds it and runs; the others wait for it, and their cores sit idle.

Every 5 ms, the switch interval, a waiting thread asks the holder to let go. The holder drops the GIL at its next check, and the operating system decides which waiting thread gets it. The work is the same 38.4 million multiply-adds, done one slice at a time, so the query takes 1.5 s (illustrative), as long as on one thread.

SCORING ONE QUERY IN 4 THREADS
from concurrent.futures import ThreadPoolExecutor


def score_range(query, start, stop):
    return [score(query, books[n]) for n in range(start, stop)]


query = books[42]
quarter = len(books) // 4               # 25,000 books per thread
starts = range(0, len(books), quarter)
stops = range(quarter, len(books) + 1, quarter)
with ThreadPoolExecutor(max_workers=4) as pool:
    parts = pool.map(score_range, [query] * 4, starts, stops)
    scores = [s for part in parts for s in part]
STEP 03 / 04

WAITING AND C CODE LET GO OF THE LOCK

Fig 6.3The accent gap is a wait; another thread runs Python while it lasts.

A thread drops the GIL whenever it is about to wait: for a socket, a file read, a lock or time.sleep(). Another thread runs Python meanwhile, and the waiting thread takes the GIL back once its data has arrived. That is why threads help a web scraper with many requests in flight.

C code can do the same. An extension that works on raw memory, not on Python objects, wraps its loop in Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS, and other threads run Python while it computes. NumPy and PyTorch release the GIL this way in their long loops (chapters 08 and 09).

STEP 04 / 04

THE FREE-THREADED BUILD RUNS THEM AT ONCE

Fig 6.4The accent bar is the same code on python3.15t: 4 cores in use at once.

The free-threaded build is CPython compiled without the GIL, installed as python3.15t. It has been supported, as an option, since 3.14, and the python.org installer for macOS installs it by default in 3.15.

Without one lock, each object needs its own protection. Objects carry two reference counts, one for the thread that made them and one shared, and a small lock each. That costs single-threaded code about 1% on macOS and up to 8% on x86-64 Linux. The 4 threads then score a query in 0.39 s (illustrative).

Every C extension has to declare that it can run without the GIL; importing one that hasn’t turns the GIL back on for the whole process. Separate processes (multiprocessing) also run in parallel, 0.38 s here, but each one needs its own copy of the catalogue.

THE SAME SCRIPT WITHOUT THE GIL
$ python3.15t -c "import sys; print(sys._is_gil_enabled())"
False
$ python3.15t similar_threads.py               # 4 threads, 4 cores at once
$ PYTHON_GIL=1 python3.15t similar_threads.py  # the GIL back on, to compare

COMMON QUESTIONS

Does asyncio get around the GIL?
No, and it doesn’t try. It runs one thread and overlaps the waiting; the async Python tutorial shows how.
Is my code thread-safe without the GIL?
The GIL never made it safe. x += 1 was never atomic, because a switch can land between its instructions. Shared mutable state still needs a threading.Lock.
How do I know whether the GIL is on?
sys._is_gil_enabled() returns False on a free-threaded build running without the GIL, and True everywhere else.

WHAT YOU NOW KNOW

  • In the default build one thread runs bytecode at a time; every 5 ms a waiting thread asks for the GIL.
  • Waits for I/O and long C loops release the GIL, so threads help I/O-bound and C-heavy work.
  • python3.15t drops the GIL for 1% to 8% single-thread cost; 4 threads then take 0.39 s per query (illustrative).
DEEP DIVE: why the GIL exists · how free-threading stays safe · processes and pickling · subinterpreters · choosing threads, processes or asyncio

Why the GIL exists

Reference counts and the allocator’s state change on almost every instruction. Protecting each of those changes with its own lock or an atomic operation would slow every single-threaded program, which was most programs when the GIL was added. One lock costs a single thread almost nothing.

C extensions came to depend on it too: code written over decades assumes nothing else touches Python objects while it runs. That assumption, more than the interpreter itself, is why removing the GIL took a separate build.

How free-threading stays safe

Biased reference counting splits the count in two: ob_ref_local for the thread that owns the object, changed without atomic instructions, and ob_ref_shared for every other thread, changed atomically. Lists and dicts lock a small per-object mutex for each operation.

Memory comes from mimalloc instead of pymalloc, and objects that many threads touch, such as functions and code objects, use immortal or deferred counts so they don’t become a point of contention. The free-threaded build has no JIT.

Processes and pickling

multiprocessing and ProcessPoolExecutor start separate interpreters, each with its own GIL. Arguments and results travel between them pickled, so sending a large catalogue to every worker costs a copy each time.

On macOS the default start method is spawn, so every worker starts a fresh interpreter and imports your module again. multiprocessing.shared_memory lets workers read one block of raw bytes without copying it.

Subinterpreters

One process can hold several interpreters. Since Python 3.12 each one can have its own GIL, so they run Python in parallel inside one process. Python 3.14 added concurrent.interpreters and InterpreterPoolExecutor to use them from Python code. Interpreters don’t share objects; data moves between them through queues.

Choosing threads, processes or asyncio

Many sockets waiting at once: asyncio, or threads if the libraries you use block. Work that spends its time in C code that releases the GIL, such as NumPy: threads. Pure-Python computation: processes, or threads on the free-threaded build once every extension you import supports it.

ERRORS THIS CHAPTER EXPLAINS

RuntimeWarning: The global interpreter lock (GIL) has been enabled to load module …
a free-threaded build imported a C extension that hasn’t declared it can run without the GIL
upgrade the package to a release with free-threaded wheels; until then the process runs with the GIL

C extensions: where Python hands work to C

So far every multiply has gone through the evaluation loop and made a new float object. But some functions you already call aren’t Python at all: len, sorted and sum are C functions inside CPython, and NumPy is a library of C that Python loads like a module. When Python calls one of them, the loop runs one instruction and the C code does the rest. How does one Python call run a whole loop at C speed, and what does crossing over cost?

STEP 01 / 04

THE MAP SO FAR

Fig 7.1The accent box is compiled code your script calls as if it were Python.

An extension module is a shared library of compiled C, C++ or Rust that the import system loads into the python3 process. To your script its functions look like Python functions, but calling one runs machine code, not bytecode. On the map it sits in the dashed band below the objects, where everything compiled that the process loads is drawn.

Extension code reads and makes Python objects through the C API: the C functions and structs CPython exports, such as PyFloat_AsDouble. The standard library’s math module is built this way. pip installs third-party extensions into site-packages, the accent folder at the top, and the import system finds them there.

STEP 02 / 04

ONE CALL TO A BUILT-IN RUNS ITS LOOP IN C

Fig 7.2The accent bar is the same scoring with the inner loop in C.

math.sumprod(query, book), in the standard library since 3.12, returns the dot product of two lists. The bookshop keeps score() and replaces its loop with that one call. In bytecode it is a single CALL instruction. Inside, a C loop reads each float’s double, multiplies and adds with extra precision for the running total, and boxes one result at the end.

Each call takes an illustrative 1.2 µs, so one query of 100,000 calls takes 0.12 s instead of 1.5 s, 12.8× faster. The night falls from 42.7 hours to 3.3 hours. Nothing else changed: the same lists of float objects, and the same evaluation loop around each call.

SIMILAR.PY: THE INNER LOOP BECOMES ONE C CALL
from math import sumprod


def score(query, book):
    return sumprod(query, book)   # one call; the 384 multiply-adds run in C
STEP 03 / 04

AN EXTENSION IS A SHARED LIBRARY THAT IMPORT LOADS

Fig 7.3Follow 1 to 5: after step 5, calling the module’s functions runs C directly.

import numpy ends at files such as _multiarray_umath.cpython-315-darwin.so. PathFinder finds it in numpy’s folder in site-packages, and ExtensionFileLoader opens it with dlopen, the operating system’s call for loading a shared library into a running process. CPython then calls the library’s init function, which builds a module object whose functions are C.

A C function receives its arguments as PyObject* pointers and works on them through the C API. The sample below is score()’s inner loop written by hand: PyList_GET_ITEM reads a slot, PyFloat_AsDouble unboxes it, plain C multiplies, and PyFloat_FromDouble boxes the one result. A wheel ships such files compiled for one Python version and platform.

FASTDOT.C: THE INNER LOOP, WRITTEN AGAINST THE C API
#include <Python.h>

/* fastdot.dot(query, book) -> float: the inner loop of score(), in C */
static PyObject *
dot(PyObject *module, PyObject *const *args, Py_ssize_t nargs)
{
    if (nargs != 2 || !PyList_Check(args[0]) || !PyList_Check(args[1])) {
        PyErr_SetString(PyExc_TypeError, "dot() takes two lists");
        return NULL;
    }
    Py_ssize_t n = PyList_GET_SIZE(args[0]);
    double total = 0.0;
    for (Py_ssize_t i = 0; i < n && i < PyList_GET_SIZE(args[1]); i++) {
        double q = PyFloat_AsDouble(PyList_GET_ITEM(args[0], i));   /* unbox */
        double b = PyFloat_AsDouble(PyList_GET_ITEM(args[1], i));
        if (PyErr_Occurred()) {
            return NULL;                      /* an item was not a number */
        }
        total += q * b;                       /* plain C arithmetic */
    }
    return PyFloat_FromDouble(total);         /* box the one result */
}
STEP 04 / 04

EVERY CROSSING COSTS, SO CROSS ONCE FOR A LOT OF WORK

Fig 7.4The accent column crosses once and finds raw numbers on the other side.

Each call from Python into compiled code is a crossing, an FFI call. It has a fixed price: the CALL instruction, checking and converting the arguments, and boxing the result. Then every element costs an unboxing, because the numbers live inside float objects. A C function called once per multiply would pay the fixed price every time and save nothing.

sumprod crosses 100,000 times per query and still unboxes 76.8 million floats from the lists. The fastest design crosses once for the whole catalogue and finds the numbers already raw on the other side, with no objects to open. Chapter 08 puts the whole catalogue across in one call.

COMMON QUESTIONS

Do I have to write C to get this?
Rarely. Cython, pybind11 or nanobind (C++) and PyO3 (Rust) write the C API calls for you. ctypes and cffi call an existing C library with no compiled wrapper of your own.
Why does pip install sometimes compile for minutes?
No wheel matched your Python version and platform, so pip built the extension from source. That needs a C compiler, and the library’s headers, on your machine.
Is sum() written in C?
Yes. Since 3.12 it has a fast path for floats that uses compensated summation, so a long sum loses less precision.

WHAT YOU NOW KNOW

  • math.sumprod runs each book’s 384 multiply-adds in one C call: 0.12 s per query instead of 1.5 s (illustrative).
  • An extension module is a .so file that import loads with dlopen; its C code reads and makes objects through the C API.
  • Each crossing costs a call plus an unboxing per element, so the fast design crosses once for a whole array of raw numbers.
DEEP DIVE: the C API and reference counting by hand · the stable ABI and abi3t · tools that write the C for you · wheels and platform tags · vectorcall

The C API and reference counting by hand

Extension code keeps reference counts itself. Py_INCREF adds one and Py_DECREF drops one, freeing the object at zero. Every C API function documents whether it returns a new reference, which the caller must release, or a borrowed one, which it must not. In the sample, PyList_GET_ITEM borrows, and PyFloat_FromDouble returns a new reference that the function hands back to Python.

Miss a release and objects are never freed, so memory grows for as long as the process runs. Release one time too many and an object is freed while something still points at it, which crashes the process later, somewhere unrelated. A module can be set up in phases (multi-phase initialisation, PEP 489), and 3.15 adds a new export hook, PyModExport_<name> (PEP 793).

The stable ABI and abi3t

An extension compiled against the full C API may use struct layouts and macros that change between versions, so it is built once per version, and the suffix .cpython-315-darwin.so says which. The stable ABI (PEP 384) is a subset whose binary interface doesn’t change. An extension limited to it is tagged abi3, ends in .abi3.so, and loads in the version it was built for and every later one.

The free-threaded build lays out objects differently, so abi3 extensions don’t load there. PEP 803, new in 3.15, adds abi3t, a stable ABI for free-threaded builds, so one compiled extension can serve several free-threaded versions too.

Tools that write the C for you

Cython (3.3.2) compiles Python-like code with optional C types into an extension module. pybind11 and nanobind wrap C++ classes and functions, and PyO3 with maturin does the same for Rust. All of them write the reference counting and argument parsing that the sample does by hand.

ctypes, in the standard library, and cffi load an existing shared library and call it with no compiled wrapper, at a higher price per call. mypyc compiles type-annotated Python into an extension module; chapter 10 compares it with Numba and Cython.

Wheels and platform tags

A wheel’s file name says where it runs. numpy-2.5.5-cp315-cp315-macosx_14_0_arm64.whl is for CPython 3.15, built against its full C API, on macOS 14 or later on Apple silicon. Linux wheels carry a manylinux tag, a promise to run on any distribution with at least a given glibc. pip picks the most specific wheel that matches and builds from source when none does.

Where wheels come from, and how a poisoned one reaches your machine, is the subject of the Python supply chain tutorial.

Vectorcall

Calling a C function once meant packing the arguments into a new tuple, and keyword arguments into a dict, on every call. PEP 590 (3.8) added vectorcall: the caller passes a C array of pointers, and the callee reads them where they are. METH_FASTCALL, the calling convention the sample uses, receives arguments the same way. Most built-ins use it, which cut the fixed price of each crossing.

ERRORS THIS CHAPTER EXPLAINS

ImportError: … symbol not found (macOS) or undefined symbol (Linux)
the .so was built against another Python or library version than the one loading it
reinstall the package in this environment so pip picks a matching wheel
RuntimeWarning: The global interpreter lock (GIL) has been enabled to load module …
an extension that hasn’t declared free-threading support, imported on python3.15t
upgrade the package to a release that supports free-threading, or accept the GIL

NumPy: one object around a block of numbers

Chapter 07 ended with the fastest design: one crossing into C, with raw numbers waiting on the other side. NumPy is that design. Its array stores the whole catalogue as 38.4 million float32 values in one block of memory, with a single Python object in front, and its operations run their loops in C over that block. Why is books @ query hundreds of times faster than the loop, and when does NumPy stop helping?

STEP 01 / 04

THE MAP SO FAR

Fig 8.1The accent box holds the numbers raw and hands matrix work to BLAS.

NumPy is an extension module, and at its centre is one extension type, the ndarray: an array object that points at a block of raw numbers and records how to read it. Operations on whole arrays run their loops in NumPy’s C code. On the map it sits in the compiled band, with its own arrow to the CPU cores.

For matrix products NumPy calls BLAS, a standard set of tuned vector and matrix routines, loaded as a library beside it. NumPy’s macOS wheels for macOS 14 and later use Apple’s Accelerate, and its Linux and Windows wheels ship OpenBLAS.

STEP 02 / 04

AN ARRAY IS ONE OBJECT AROUND RAW NUMBERS

Fig 8.2The accent slice is one book: 1,536 bytes, the same 384 numbers that took 12,344 bytes as a list.

The catalogue as an array, books, has the dtype float32: every element is a 4-byte float with no object around it. Its shape is (100000, 384), and its buffer is one block of 153.6 MB, against about 1.23 GB as lists of float objects. NumPy’s documentation describes an array as “a contiguous one-dimensional segment of computer memory” combined with an indexing scheme.

The strides, (1536, 4), are that scheme: step 1,536 bytes to reach the next book and 4 to reach the next number. So books[42] starts 42 strides of 1,536 bytes into the buffer. Slicing it makes a view: a new array object over the same buffer, with nothing copied.

THE CATALOGUE AS ONE ARRAY
import numpy as np

books = np.load("embeddings.npy")
books.dtype      # dtype('float32')
books.shape      # (100000, 384)
books.strides    # (1536, 4): bytes to the next book, to the next number
books.nbytes     # 153600000
row = books[42]  # a view into the same buffer: nothing is copied
STEP 03 / 04

ONE CALL SCORES EVERY BOOK

Fig 8.3Follow 1 to 6: Python runs one instruction at 1, and compiled code does the rest.

scores = books @ query is one BINARY_OP (@) instruction. NumPy checks the shapes and the dtype once, releases the GIL, and calls BLAS’s matrix-vector routine, sgemv, with a pointer to the buffer. The 38.4 million multiply-adds then run as machine code: SIMD instructions, each working on several float32 values at once, spread over several cores.

This is vectorization: one call over a whole array, so the loop runs in compiled code over raw numbers. One query takes an illustrative 3 ms, 512× faster than the pure loop’s 1.5 s. np.argpartition then finds the 11 best scores, the book itself among them, without sorting all 100,000.

ONE QUERY AGAINST THE WHOLE CATALOGUE
query = books[42]
scores = books @ query                          # 100,000 dot products in one call
top = np.argpartition(scores, -11)[-11:]        # the 11 best, in no order
top = top[np.argsort(scores[top])[::-1]][1:]    # best first, the book itself dropped
STEP 04 / 04

DO MORE WORK PER CALL AND IT GETS FASTER STILL

Fig 8.4The accent row does the same arithmetic in 100 calls instead of 100,000.

One book per call, the night is 100,000 calls of 3 ms: 5 minutes (illustrative). Each call reads the whole 153.6 MB buffer from memory to do one multiply and one add per number, so the cores spend most of the call waiting for data to arrive, not computing.

With 1,000 query books per call, block @ books.T is a matrix-matrix product. BLAS keeps pieces of both matrices in the CPU’s cache and uses each number it fetches for many query books before fetching the next. The night’s 7.68 trillion floating-point operations then run in 100 calls at an illustrative 1 trillion a second: 7.7 s.

THE NIGHT IN BLOCKS OF 1,000 BOOKS
for start in range(0, len(books), 1000):
    block = books[start:start + 1000]           # 1,000 query books
    scores = block @ books.T                    # 1,000 × 100,000 scores in one call
    best = np.argpartition(scores, -11, axis=1)[:, -11:]

COMMON QUESTIONS

float32 or float64 for embeddings?
Usually float32: half the memory and twice as many values per SIMD instruction, with enough precision to rank neighbours. NumPy defaults to float64, so ask for float32 when you create or load the array.
Why is NumPy slow on tiny arrays?
Each call still pays for the crossing, the shape and dtype checks and a new result object. For ten numbers, a plain Python loop can win.
How many threads does BLAS use?
Usually one per core. Set OPENBLAS_NUM_THREADS, or use threadpoolctl, to limit it when you also run several processes.

WHAT YOU NOW KNOW

  • books is one object around a 153.6 MB float32 buffer, with shape (100000, 384) and strides (1536, 4).
  • books @ query runs one instruction in Python and the rest in BLAS, with SIMD on several cores: 3 ms per query (illustrative).
  • Scoring 1,000 books per call turns the night from 5 minutes into 7.7 s (illustrative).
DEEP DIVE: views and copies · broadcasting · ufuncs and SIMD · BLAS backends · temporaries and memory · NumPy without the GIL

Views and copies

Basic slicing, such as books[42] or books[:1000], returns a view: a new array object with its own shape and strides over the same buffer. Writing through a view changes the original. np.shares_memory(a, b) says whether two arrays overlap, and .copy() makes an independent one.

A view can be non-contiguous: books[:, :64] keeps the 1,536-byte row stride but reads only part of each row. Some routines need contiguous input and copy it first; np.ascontiguousarray makes that copy explicit, and books.flags['C_CONTIGUOUS'] tells you whether you need it.

Broadcasting

Arithmetic between arrays of different shapes stretches the smaller one along the missing dimension, without copying it. To normalise every embedding, books / np.linalg.norm(books, axis=1, keepdims=True) divides each row of the (100000, 384) array by its own length, held in an array of shape (100000, 1). After that, the dot product of two books is their cosine similarity.

ufuncs and SIMD

Element-by-element operations such as add, multiply and sqrt are ufuncs, universal functions: one C loop per dtype. NumPy writes those loops once with its universal intrinsics, a layer over each CPU’s SIMD instructions, and compiles several versions. At import it picks the version the CPU supports. Sorting uses Google’s Highway library instead.

BLAS backends

np.show_config() prints the BLAS a NumPy build uses. The macOS wheels for macOS 14 and later link Apple’s Accelerate, Linux and Windows wheels bundle OpenBLAS, and some conda builds use Intel’s Math Kernel Library. The same @ runs at different speeds on each, so a benchmark should name its BLAS along with its machine.

Temporaries and memory

a * b + c makes a temporary array for a * b, then another for the sum. With arrays the size of the catalogue, each temporary is another 153.6 MB. np.multiply(a, b, out=buf) writes into an array you already have, and a *= b works in place.

NumPy without the GIL

NumPy’s documentation says “many NumPy operations release the GIL”, so threads that spend their time in large array operations do run in parallel, even on the default build. NumPy has supported the free-threaded build experimentally since 2.1, and 2.5.5 ships cp315t wheels for python3.15t.

PyTorch and the GPU: Python decides, the GPU computes

The blocked NumPy night is 7.7 s of arithmetic on the CPU (illustrative). A GPU has thousands of simple cores and memory fast enough to feed them, and machine-learning work is mostly the same matrix products. But the code that drives the GPU in almost every machine-learning project is Python, the language that needed 42.7 hours for this job. If Python is slow, how does it keep a GPU busy, and why does AI use it at all?

STEP 01 / 05

THE MAP SO FAR

Fig 9.1The accent parts take a Python call and turn it into work on the GPU.

Two parts are new. PyTorch is the module torch: a thin Python layer over torch._C, an extension module written in C++ that holds ATen, PyTorch’s library of operators. Its array is the tensor, which works like a NumPy array but can also live in a GPU’s memory.

The GPU is a separate processor on its own card, with thousands of simple cores and its own memory. Programs for it are written with NVIDIA’s CUDA, and the GPU computes on data in its own memory, so the catalogue is copied there before any work starts. On the map, PyTorch’s arrow runs to the GPU, and NumPy’s to the CPU cores.

STEP 02 / 05

A TORCH CALL QUEUES A KERNEL AND RETURNS

Fig 9.2Follow 1 to 7: Python is free again at 4, while the accent kernel is still running.

The @ in block @ books_gpu.T is one bytecode instruction, and it calls into torch._C. There the dispatcher looks at the tensors. It passes them through the autograd layer, which records the operation in case gradients are needed, then picks the implementation for their device, CUDA. ATen hands the product to cuBLAS, NVIDIA’s BLAS, which supplies the kernel, the function that runs on the GPU.

The kernel doesn’t run during the call. PyTorch puts it on a CUDA stream, a queue the GPU works through in order, and returns at once with a tensor whose values don’t exist yet. Python moves to its next line while the GPU computes. Anything that reads the values, such as .cpu(), .item() or print(scores), waits until the work queued before it has finished.

THE NIGHT IN PYTORCH: 3 CALLS PER BLOCK, ONE WAIT AT THE END
import time

import torch

torch.set_float32_matmul_precision("high")      # allow TF32 matrix products
books_gpu = torch.from_numpy(books).to("cuda")  # 153.6 MB copied to the GPU once

start = time.perf_counter()
results = []
for first in range(0, len(books_gpu), 1000):
    block = books_gpu[first:first + 1000]       # call 1: a view of 1,000 books
    scores = block @ books_gpu.T                 # call 2: queues the product, returns at once
    results.append(scores.topk(11, dim=1).indices)  # call 3: queues top-k
torch.cuda.synchronize()                         # wait for the GPU before reading the clock
print(time.perf_counter() - start)
STEP 03 / 05

THE NIGHT IS 100 MATRIX PRODUCTS

Fig 9.3The accent line is where the night goes: matrix products on the GPU.

The catalogue is copied to the GPU once: 153.6 MB at an illustrative 25 GB/s takes 6.1 ms. Then the job walks through 100 blocks of 1,000 books. Each block’s product is 76.8 billion floating-point operations, and at an illustrative sustained 300 TFLOPS it takes 0.256 ms. Picking each block’s top 10 with topk adds 0.05 ms.

The products run in TF32, which set_float32_matmul_precision("high") allows: float32’s range with fewer digits, which the GPU’s matrix hardware runs much faster. NVIDIA’s datasheet gives the H100 SXM about 494 TFLOPS of dense TF32 and 67 TFLOPS of plain float32, so the example’s sustained 300 sits below the TF32 peak.

Python’s side is 300 calls, 3 per block, at an illustrative 5 µs each: 1.5 ms. Each call only queues work, so the queueing overlaps the GPU’s 30.6 ms of computing. The night is 36.7 ms, about 0.04 s, against 42.7 hours for the pure-Python loop.

STEP 04 / 05

SMALL OPERATIONS LEAVE THE GPU WAITING ON PYTHON

Fig 9.4The accent bar keeps the GPU busy; the slivers above leave it waiting for Python.

Write the same query one book at a time, books_gpu[j] @ query in a Python loop. That is two torch calls per book, the index and the product, each an illustrative 5 µs of Python and dispatcher work. One query takes 1 s, slower than NumPy’s 3 ms on the CPU. Each kernel finishes in microseconds, and the GPU sits idle while Python launches the next.

So the fix is fewer, bigger calls: one matrix product per block does the same arithmetic in 3 calls. When the calls can’t grow, a CUDA Graph records a sequence of launches once and replays it with one call, and torch.compile turns a function into fewer, fused kernels.

torch.compile works through CPython itself. Its front end, Dynamo, hooks into frame evaluation through PEP 523, reads your function’s bytecode and turns the torch calls in it into a graph. Its back end, Inductor, generates fused GPU kernels in Triton, a Python-like language for writing kernels. The first call compiles; later calls with the same shapes reuse the result.

TORCH.COMPILE: ONE DECORATOR, FUSED KERNELS AFTER THE FIRST CALL
import torch


@torch.compile
def neighbours(block, books_gpu):
    return (block @ books_gpu.T).topk(11, dim=1).indices


# The first call traces the function's bytecode and generates kernels;
# later calls with the same shapes and dtypes reuse them.
STEP 05 / 05

PYTHON LEADS IN AI BECAUSE THE HEAVY WORK ISN’T IN PYTHON

Fig 9.5The accent row does the arithmetic; the Python rows above it decide what to compute.

Go back to the receipt. Of the night’s 36.7 ms, Python and the dispatcher spend 1.5 ms on 300 calls, about 4%, all of it while the GPU works. The kernels take 83% and the copy 17%, and neither runs a line of Python: the arithmetic is cuBLAS and ATen, written in C++ and CUDA. So the job’s speed depends on how few calls Python makes, hardly on how fast it makes them.

What the main language needs, then, is what Python is good at: short readable code, notebooks for trying ideas, and a C API that makes fast libraries easy to wrap. In 1998 Python’s creator, Guido van Rossum, wrote that Python is used “to glue together large software components”. NumPy (1.0 in 2006) wrapped C and BLAS that way, and PyTorch, JAX and Hugging Face’s libraries later did the same for GPUs.

The surveys show where that led. In Stack Overflow’s 2025 Developer Survey, 57.9% of respondents used Python, which the survey calls “the go-to language for AI, data science, and back-end development”. In the 2024 Python Developers Survey by JetBrains and the Python Software Foundation, 38% of respondents train or run machine-learning models, and 66% of those use PyTorch. For what the products compute in a language model, read How a transformer works.

COMMON QUESTIONS

Is JAX or TensorFlow any different?
Same pattern. Python traces your function into a graph (a jaxpr in JAX), and a compiler turns that graph into kernels for the device. Python decides what to compute; compiled code computes it.
Do I need CUDA C++ to write a fast GPU kernel?
Not always. Triton lets you write GPU kernels in a Python-like language, and torch.compile generates Triton code for you. For standard operations, PyTorch already ships tuned kernels.
Does the GIL matter here?
Little. PyTorch releases it during long operations, and one thread can queue work far faster than the GPU finishes it.

WHAT YOU NOW KNOW

  • A torch call goes through the dispatcher, queues a CUDA kernel on a stream and returns before the GPU has finished.
  • The night is 100 matrix products: 36.7 ms in total, with Python’s 300 calls taking 1.5 ms (illustrative).
  • Python leads in AI because the arithmetic runs in C++ and CUDA, and Python only decides what to run next.
DEEP DIVE: dispatch keys and autograd · synchronisation points · CUDA Graphs · torch.compile · JAX and Triton · why Python won

Dispatch keys and autograd

For every operator, the dispatcher keeps a table of kernels by dispatch key: one for CPU tensors, one for CUDA tensors, one for the autograd layer, and others for features such as tracing. A call walks the keys that apply to its tensors in priority order, so autograd runs first, records what it needs for gradients, then hands the call down to the CUDA kernel.

torch.no_grad() and torch.inference_mode() skip that recording. A nightly job that only scores books can wrap its loop in inference_mode() and save the autograd work on every call.

Synchronisation points

Some calls need a value on the CPU, so they wait for the GPU: .item(), .cpu(), print(tensor), and if tensor:, which needs a Python bool. One of them inside the block loop makes every iteration wait for the queue to empty, and Python’s calls stop overlapping the GPU’s work.

To time GPU work, call torch.cuda.synchronize() before reading the clock, or record a pair of torch.cuda.Event(enable_timing=True) on the stream and read the time between them.

CUDA Graphs

NVIDIA measured 3.8 µs per tiny kernel including launch overhead, and 3.4 µs when the same kernels ran as one graph (V100, 2019). PyTorch’s post on CUDA Graphs reports the graphed part of a Mask R-CNN model going from 31 ms to 6 ms.

A graph is recorded once with torch.cuda.graph and replayed with replay(). The shapes and memory addresses must stay the same between replays, so inputs are copied into fixed tensors first. torch.compile(mode="reduce-overhead") records graphs for you.

torch.compile

Dynamo installs a frame-evaluation hook through PEP 523, so CPython hands it each frame before running it. It reads the bytecode, records the torch operations into a graph and adds guards on the inputs’ shapes, dtypes and devices; a call that fails a guard compiles again. Code it can’t follow, such as a call into an unknown C library, causes a graph break: that part runs as plain Python.

Inductor turns each graph into Triton kernels for GPUs and C++ for CPUs, fusing elementwise steps into one kernel so data crosses memory fewer times. In PyTorch 2.15.0, torch.compile works on Python 3.11 to 3.15.

JAX and Triton

jax.jit traces a Python function once into a jaxpr, a small typed program of array operations, and a compiler turns that into code for the device. Python runs once per trace, not once per element or per call.

Triton, which OpenAI announced in 2021, is a Python-like language for GPU kernels, built so that “researchers with no CUDA experience” can write them. Inductor emits Triton code, so most PyTorch users run Triton kernels without writing one.

Why Python won

GitHub’s Octoverse 2024 report found that Python had overtaken JavaScript on GitHub. Octoverse 2025 found that TypeScript passed Python by number of contributors in August 2025, and that Python “remains dominant in AI and data science”.

The ecosystem is older than deep learning. NumPy grew out of two earlier array packages, Numeric (mid-1990s) and Numarray, and NumPy 1.0 was tagged in October 2006. GPU libraries took over its arrays and its users, and torch.from_numpy still shares a NumPy array’s memory without a copy.

Other implementations: PyPy, GraalPy, MicroPython, Pyodide

Everything so far happened inside CPython, because that is what python3 almost always is. But chapter 01 said Python is a language, and several other programs run it, each built for a different need: faster pure-Python loops, running inside a Java application, fitting on a microcontroller, or running in a web browser. Some tools keep CPython and compile parts of your code instead. When should something other than CPython run your code, and what does it cost you?

STEP 01 / 04

THE MAP SO FAR

Fig 10.1The accent column replaces the whole process box, not one part of it.

The column on the right of the map holds four other implementations: PyPy, GraalPy, MicroPython and Pyodide. Each is a whole program that reads similar.py and runs it, so it replaces the entire python3 box: its own compiler, its own loop, its own objects and its own way of loading C extensions, if it loads them at all.

That is a different move from chapters 07 to 09, where an extension module, NumPy or PyTorch ran inside CPython and left the rest of the map in place. The last step of this chapter returns to that side: tools that keep CPython and compile one hot function.

STEP 02 / 04

PYPY TRACES THE HOT LOOP AND COMPILES IT WITH RAW FLOATS

Fig 10.2Follow 1 to 5: the accent box keeps the floats raw, and a failed guard returns to the interpreter.

PyPy 8.0.1 implements Python 3.11, with 3.12 in beta. It is written in RPython, a restricted subset of Python, and its tracing JIT is generated from that interpreter rather than written by hand. When a loop gets hot, PyPy records the operations of one iteration as a trace, with a guard for every type it assumed.

The optimiser then removes the float objects: query[i], book[i] and their product stay doubles in CPU registers, and only the guards remain. The compiled loop runs the pure score() in an illustrative 60 ms per query, 25.6× faster than CPython’s 1.5 s. Across the benchmarks on speed.pypy.org, PyPy averages about 3.5 times as fast as CPython 3.11.

The costs come with that design. C extensions run through cpyext, a layer that imitates CPython’s C API and is slow, so NumPy code can get slower on PyPy. PyPy also has no reference counting: its garbage collector frees objects later, so __del__ methods run and files close later than on CPython.

PYPY: THE SAME SCRIPT, ANOTHER PROGRAM
$ pypy3 --version                 # PyPy 8.0.1 implements Python 3.11
$ pypy3 similar.py                # the pure-Python job, unchanged
STEP 03 / 04

EACH IMPLEMENTATION ANSWERS A DIFFERENT NEED

Fig 10.3Read the accent row first; the rows above explain each answer.

GraalPy 25.6.5 is “a Python 3.13 compliant runtime” on GraalVM, Oracle’s Java runtime with its own JIT compiler. Java applications embed it as a library and call Python directly, in the same process. Its support for C extensions is experimental, though NumPy and PyTorch install.

MicroPython 1.29.0 implements Python 3.4 plus some later features, with a much smaller standard library. It compiles to its own bytecode, which mpy-cross can also produce ahead of time as .mpy files, and it runs on microcontrollers such as the RP2040, RP2350 and ESP32, with a few hundred kilobytes of RAM.

Pyodide 314.0.8 is CPython 3.14 compiled to WebAssembly with Emscripten, so it runs in a web browser and can install pure-Python wheels and its own builds of NumPy. Two older implementations stopped long ago: Jython, on Java, at Python 2.7, and IronPython, on .NET, at Python 3.4.

STEP 04 / 04

OR KEEP CPYTHON AND COMPILE THE HOT FUNCTION

Fig 10.4The accent column needs one decorator and no build step.

Numba 0.68.1 compiles a decorated function to machine code with LLVM the first time it is called with a given set of argument types. With @njit on score and two float32 arrays as input, the loop runs on raw floats in an illustrative 20 ms per query, 76.8× faster than the pure loop, inside CPython and with no build step.

Cython 3.3.2 compiles Python-like code with C type declarations into C, built into an extension module. mypyc, shipped with mypy 2.4.1, compiles ordinary type-annotated Python the same way; mypy itself is compiled with it, for “a 4x performance improvement”. Codon compiles a Python-like language to machine code, but it isn’t compatible with CPython.

NUMBA: ONE DECORATOR, COMPILED AT THE FIRST CALL
import numpy as np
from numba import njit


@njit(fastmath=True)
def score(query, book):
    total = np.float32(0.0)
    for i in range(query.shape[0]):
        total += query[i] * book[i]
    return total


score(books[0], books[1])   # the first call compiles score for two float32 arrays

COMMON QUESTIONS

Should the bookshop switch to PyPy?
No. Its job is fastest in NumPy and PyTorch, which PyPy runs only through the slow cpyext layer.
Is MicroPython “real” Python?
It runs Python 3.4 syntax plus some later features, with a much smaller standard library, on chips with a few hundred kilobytes of RAM.
Can Python run in a browser?
Yes. Pyodide is CPython compiled to WebAssembly, and it can install pure-Python wheels and its own builds of NumPy.

WHAT YOU NOW KNOW

  • PyPy compiles the hot score() loop with unboxed floats: 60 ms per query (illustrative), but C extensions get slower.
  • GraalPy embeds in Java, MicroPython fits on a microcontroller, and Pyodide runs CPython in a web browser.
  • Numba, Cython and mypyc keep CPython and compile one hot function; Numba’s @njit runs score in 20 ms (illustrative).
DEEP DIVE: how PyPy’s JIT is generated · cpyext and HPy · GraalPy and Truffle · MicroPython’s bytecode and .mpy · Pyodide and WebAssembly · retired implementations

How PyPy’s JIT is generated

PyPy’s interpreter is written in RPython, and a translation toolchain compiles it to C. The same toolchain generates the JIT from the interpreter: hints mark the interpreter’s dispatch loop, and the JIT traces the interpreter while it runs your loop. This is called meta-tracing, and any language interpreter written in RPython gets a JIT the same way.

Memory is managed by incminimark, a generational collector, with no reference counts. An object is freed when the collector next runs, not when its last reference goes. For the method-at-a-time JITs of V8 and HotSpot, read the JIT chapter of Interpreted vs compiled.

cpyext and HPy

PyPy’s objects don’t have CPython’s memory layout, so cpyext has to present each object a C extension touches as a PyObject* and keep the two in step. That bookkeeping runs on every crossing, which is why a C-heavy program can run slower on PyPy than on CPython.

HPy is a C API designed to avoid that cost, so one extension build could run fast on both; version 0.9.0 came out in 2023. PyPy 8.0 dropped its HPy backend.

GraalPy and Truffle

GraalPy is built on Truffle, GraalVM’s framework for interpreters written in Java, which the Graal compiler turns into machine code. A Java program creates a Python context and calls Python functions in its own process, with no second runtime to manage.

Since 25.6, Oracle runs a wheel index with GraalPy builds of popular packages. The project’s own README claims GraalPy is “~4x faster” than CPython on the pyperformance benchmarks.

MicroPython’s bytecode and .mpy

MicroPython compiles source to its own compact bytecode on the device. mpy-cross does the same ahead of time and writes .mpy files, so the board skips the compile step. Ports cover the RP2040 and RP2350, the chips on Raspberry Pi Pico boards, and the ESP32, among others. CircuitPython is Adafruit’s fork of MicroPython.

Pyodide and WebAssembly

Pyodide builds CPython with Emscripten 5.0.3, a compiler from C and C++ to WebAssembly. PEP 776 made Emscripten a Tier 3 platform for CPython 3.14. PEP 11 lists wasm32-unknown-wasip3 as Tier 2: WebAssembly outside the browser, through the WebAssembly System Interface.

Retired implementations

Jython runs Python on Java and supports Python 2.7 only; its latest release is 2.7.5rc2, from 2026. IronPython 3.4.2 targets Python 3.4 on .NET. RustPython, an interpreter written in Rust, has published only pre-release versions.

The whole picture

Here is every part again, each with a number that matches a row of the table below.

Find a number on the map, then its row below: what the part does, where it sits and what it decides.

ONE NIGHT, FIVE WAYS (ILLUSTRATIVE)

The same similar-books job, from the slowest version to the fastest. Each step moves the loop further from the evaluation loop (5): into a C function (10), into NumPy and BLAS (11), then onto the GPU (12, 13).

pure Python
42.7 hours
math.sumprod
3.3 hours
NumPy, one book per call
5 minutes
NumPy, 1,000 books per call
7.7 s
GPU, 1,000 books per call
0.04 s
  1. 1CPython (python3)

    the C program that compiles and runs your Python

    where it sits
    one operating-system process per run
    decides
    which Python version and which sys.path your code gets
    when wrong
    code that works on your laptop and fails on a server with another Python
  2. 2import system

    finds each module on sys.path and loads it once

    where it sits
    the interpreter, through sys.meta_path
    decides
    which file an import statement actually loads
    when wrong
    ModuleNotFoundError, or your own random.py loaded instead of the standard one
  3. 3.pyc cache

    keeps the bytecode of imported modules for the next start

    where it sits
    a __pycache__ folder beside each module
    decides
    whether a module is recompiled, by comparing the source’s time and size
    when wrong
    slow starts in read-only containers that recompile every module every time
  4. 4compiler

    turns source text into code objects full of bytecode

    where it sits
    inside the process, before any line of the file runs
    decides
    which names become numbered local slots and which stay global lookups
    when wrong
    a SyntaxError before anything runs, pointing at the line it couldn’t parse
  5. 5evaluation loop

    runs bytecode one instruction at a time, each call in its own frame

    where it sits
    every thread that runs Python code
    decides
    nothing about types; it runs each instruction in order
    when wrong
    pure-Python loops that take seconds where compiled code takes milliseconds
  6. 6objects

    hold every value, each with a reference count and a type

    where it sits
    the process’s memory, shared by all its threads
    decides
    when a value is freed: at zero references, or by the cycle collector
    when wrong
    memory far above the data’s size, such as a gigabyte of floats in lists
  7. 7specializer

    rewrites hot instructions for the types they keep seeing

    where it sits
    inside the evaluation loop, always on since Python 3.11
    decides
    which fast version of an instruction runs, behind a type check
    when wrong
    a hot loop slower than expected because its value types keep changing
  8. 8JIT

    compiles hot loops into machine code while the program runs

    where it sits
    beside the evaluation loop, in builds that include it
    decides
    nothing until it is switched on; then which loops become machine code
    when wrong
    PYTHON_JIT=1 changing nothing, because the build has no JIT
  9. 9GIL

    lets one thread at a time run Python bytecode

    where it sits
    the interpreter, shared by all of its threads
    decides
    which thread may run Python, handing over every 5 ms
    when wrong
    four busy threads finishing no faster than one
  10. 10C extensions

    run compiled C code that Python imports and calls like a module

    where it sits
    .so files in site-packages, loaded with dlopen
    decides
    nothing on their own; they do the work Python asks for
    when wrong
    an ImportError about a missing symbol after upgrading Python
  11. 11NumPy and BLAS

    store numbers raw and loop over them in compiled code

    where it sits
    NumPy’s extension, which loads a BLAS library
    decides
    how each array operation runs, using SIMD and every core
    when wrong
    a Python loop over an array running slower than one over a list
  12. 12PyTorch

    sends each tensor operation to a C++ or GPU kernel

    where it sits
    torch._C, an extension that holds the dispatcher
    decides
    which kernel runs, from the tensor’s device and whether it records gradients
    when wrong
    a GPU that sits mostly idle while Python launches tiny operations
  13. 13GPU

    runs matrix kernels in its own memory, apart from Python

    where it sits
    a PCIe device fed through CUDA streams
    decides
    nothing; it runs kernels in the order they were queued
    when wrong
    timings that look instant because nothing waited for the GPU
  14. 14other implementations

    run the same Python language with a different design

    where it sits
    replace CPython as the whole process
    decides
    how loops are compiled and whether C extensions run at full speed
    when wrong
    a package that won’t install, or NumPy code that gets slower on PyPy

THREE THINGS TO KEEP

  • CPython compiles your code to bytecode, then a loop written in C runs it one instruction at a time.
  • Each Python operation costs much more than the arithmetic it does, so fast programs hand whole loops to compiled code.
  • In machine learning Python only decides what the GPU computes next, so its own speed hardly matters.
Read next. Interpreted vs compiled for the same pipeline in V8, the JVM and Go, Async Python for one thread that waits on many sockets, and How a transformer works for the matrix products a GPU spends its time on.
$ python3 similar.py
done in 0.04 s (illustrative)
Next time a Python job is slow, ask which loop is still running in Python.