Python 3.9 and the Road to a Faster CPython

Contents
Python 3.9.1 came out last week. Built from their tags with the same compiler on the same machine,
four releases of CPython, 3.6.5 to 3.9.1, run the same loop of integer arithmetic in the same
0.36 seconds, give or take a hundredth. Calling a method got 24% cheaper over those releases, and
calling range(10) got 24% cheaper in 3.9 alone. And the slow program from Part 13, the one whose
time went to the cycle collector, runs 44% slower on 3.8 than on 3.7, with the same number of
collections, because each collection got slower.
This last post of the series does three things. It looks under 3.9, at its new parser and at the groundwork it lays for running several interpreters apart. It measures the same programs across every CPython this series has used. And it looks at the plans for a faster CPython that appeared this autumn, and back over the places, one per post, where Python turned out to be C.
This is Part 17 of a series on the CPython runtime, and the last. It is written for Python programmers
who have written a little C. Everything here ran on CPython 3.6.5, 3.7.0, 3.8.0 and 3.9.1, the first
releases this series used of each minor version and the newest, all built from their tags with Ubuntu
20.04’s gcc 9.3 and the default ./configure options. The note at the end says exactly where and how.
A new parser
Every Python program is text before it is anything else, and since 1990 CPython turned that text into a
tree with a parser generated from Grammar/Grammar by Guido van Rossum’s own generator, pgen. pgen
makes LL(1) parsers: at each step the parser decides what it’s looking at from the next single token.
Python’s grammar was bent to fit. Where it couldn’t be, the parser accepted a superset and a second pass
in Python/ast.c threw out what wasn’t legal, which is why a line like f(x) = 1 is rejected late, by
code written by hand.
3.9 replaces it, under PEP 617, with a PEG parser generated from Grammar/python.gram. A PEG parser
tries the alternatives of a rule in order and backtracks when one fails, so it can look as far ahead as
it needs, and it memoises results so that the backtracking doesn’t repeat work. The grammar file now
says directly which AST node each rule builds, so the second pass is gone. The old parser is still in
3.9, behind -X oldparser, and is due to be removed in 3.10. That makes this the release where both can
be measured on the same input. Here they parse every .py file in 3.9.1’s standard library:
import ast, glob, os, resource, sys, time
files = sorted(glob.glob(os.path.join(os.path.dirname(os.__file__), "**", "*.py"), recursive=True))
sources = []
for name in files:
try:
with open(name, encoding="utf-8") as f:
sources.append(f.read())
except (UnicodeDecodeError, OSError):
pass
rss_before = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
t = time.perf_counter()
errors = 0
for src in sources:
try:
ast.parse(src)
except SyntaxError:
errors += 1
elapsed = time.perf_counter() - t
rss_after = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
print("%-10s %d files, %.1f MB: parsed in %.2f s, %d SyntaxErrors, peak memory grew %d MB" % (
"oldparser" if "oldparser" in sys._xoptions else "PEG", len(sources),
sum(map(len, sources)) / 1e6, elapsed, errors, (rss_after - rss_before) // 1024))
$ /opt/py/f3.9.1/bin/python3 parsebench.py
PEG 2175 files, 34.4 MB: parsed in 2.33 s, 8 SyntaxErrors, peak memory grew 30 MB
$ /opt/py/f3.9.1/bin/python3 -X oldparser parsebench.py
oldparser 2175 files, 34.4 MB: parsed in 2.24 s, 8 SyntaxErrors, peak memory grew 32 MB
On real code the two are close: the PEG parser was 4% slower and used about 2 MB less memory at its peak, and eight files failed in each, test data written to be invalid on purpose. PEP 617’s own benchmarks found the new parser within 10% of the old one, and that’s what this is. The point of the change isn’t speed. It’s that the grammar can now say what the language is, without a hand-written pass to patch it.
And for now, the grammar says slightly more than the language:
src = "with (open('/dev/null') as a,\n open('/dev/null') as b):\n pass\n"
try:
compile(src, "<test>", "exec")
print("accepted")
except SyntaxError as e:
print("SyntaxError:", e.msg)
$ /opt/py/f3.9.1/bin/python3 withparen.py
accepted
$ /opt/py/f3.9.1/bin/python3 -X oldparser withparen.py
SyntaxError: invalid syntax
$ /opt/py/f3.8.0/bin/python3 withparen.py
SyntaxError: invalid syntax
A with statement with its context managers in parentheses, split across lines, has been wanted for
years and couldn’t be expressed in LL(1): an opening parenthesis after with could start a tuple
expression or a group of as clauses, and one token isn’t enough to tell. 3.9.1’s PEG parser accepts it,
the old parser in the same binary rejects it, and the language reference for 3.9 doesn’t mention it. It
works by accident of the implementation, which is the purest case of this series’ subject: what Python
accepts is what CPython’s C accepts. Code written for it runs on 3.9.1’s default parser and on nothing
else today.
Calls, again
Part 12 measured PEP 590’s vectorcall, the calling convention 3.8 introduced, and found most calls
didn’t move. In 3.9 the built-in types adopted it as constructors: range, list, tuple, dict,
set, frozenset and others can now be called without first packing their arguments into a tuple and
a dict. The measurements below, from the cross-version run later in this post, show it on list(),
dict() and range(10): 17.6, 27.9 and 33.7 ns in 3.9.1, against 20.0, 32.5 and 44.3 in 3.8.0.
Calling a type is one of the most common operations in Python and one of the least visible, and a third
of the cost of range(10) was argument packing.
The groundwork for interpreters that can start over
Part 15 found that a C extension imported a second time doesn’t run its initialisation again: for
single-phase modules, CPython keeps a copy of the first module’s dictionary in m_copy and makes the
new module from that. Part 16 found why that matters beyond reimporting. Interpreters in one process share
everything that’s static in C, and they share a GIL because of it. The way out is for each extension
module to keep its state in the module object, created fresh for each interpreter. That’s PEP 489’s
multi-phase initialisation, available since 3.5, and PEP 573, new in 3.9, which lets a C method find
its own module’s state without going through a global. 3.9 converted a long list of standard library
extension modules. This tests every module in lib-dynload, on each version, by importing it, removing
it, importing it again and checking whether its functions are new objects, which means its
initialisation ran again:
import os, subprocess, sys
probe = r'''
import importlib, sys
name = sys.argv[1]
m = importlib.import_module(name)
fns = [k for k, v in sorted(vars(m).items()) if type(v).__name__ == "builtin_function_or_method"]
if not fns:
print("none"); sys.exit()
before = getattr(m, fns[0])
del sys.modules[name]
again = importlib.import_module(name)
print("copied" if getattr(again, fns[0]) is before else "fresh")
'''
dyn = os.path.join(sys.prefix, "lib", "python%d.%d" % sys.version_info[:2], "lib-dynload")
names = sorted(f.split(".")[0] for f in os.listdir(dyn) if f.endswith(".so"))
result = {}
for name in names:
r = subprocess.run([sys.executable, "-c", probe, name], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
result.setdefault(r.stdout.strip() or "failed", []).append(name)
print("Python %s: %d extension modules in lib-dynload; fresh on reimport: %d, copied: %d, no functions or failed: %d" % (
sys.version.split()[0], len(names), len(result.get("fresh", [])), len(result.get("copied", [])),
len(result.get("none", [])) + len(result.get("failed", []))))
print(" fresh:", " ".join(result.get("fresh", [])))
$ for v in 3.6.5 3.7.0 3.8.0 3.9.1; do /opt/py/f$v/bin/python3 reimport.py; done
Python 3.6.5: 65 extension modules in lib-dynload; fresh on reimport: 12, copied: 44, no functions or failed: 9
fresh: _codecs_cn _codecs_hk _codecs_iso2022 _codecs_jp _codecs_kr _codecs_tw _csv _curses_panel _testmultiphase array readline xxlimited
Python 3.7.0: 69 extension modules in lib-dynload; fresh on reimport: 13, copied: 47, no functions or failed: 9
fresh: _codecs_cn _codecs_hk _codecs_iso2022 _codecs_jp _codecs_kr _codecs_tw _csv _curses_panel _testmultiphase _xxtestfuzz array readline xxlimited
Python 3.8.0: 73 extension modules in lib-dynload; fresh on reimport: 14, copied: 50, no functions or failed: 9
fresh: _codecs_cn _codecs_hk _codecs_iso2022 _codecs_jp _codecs_kr _codecs_tw _csv _curses_panel _testmultiphase _xxtestfuzz array binascii readline xxlimited
Python 3.9.1: 74 extension modules in lib-dynload; fresh on reimport: 27, copied: 37, no functions or failed: 10
fresh: _codecs_cn _codecs_hk _codecs_iso2022 _codecs_jp _codecs_kr _codecs_tw _contextvars _crypt _csv _ctypes_test _curses_panel _heapq _json _statistics _struct _testmultiphase _uuid _xxtestfuzz array audioop binascii math readline resource select syslog xxlimited
From 12 modules that start over to 27 in one release: math, select, _json, _struct, _heapq and
others joined in 3.9. (“Fresh” also counts modules that were already fresh in 3.6, like the CJK codecs and
array.) Most of the standard library’s extensions, and nearly all
third-party ones, are still single-phase. Each one converted is one less piece of process-wide state
standing between CPython and interpreters with a GIL each, which is the goal of the people doing this
work and, as Part 16 showed, a long way off.
Four versions, one machine
This is the measurement I’ve wanted since Part 1: the same small programs on every CPython in this series, built by one compiler, run in one sitting. The script below alternates the versions in three rounds, forwards and backwards, and keeps each measurement’s best, so a slow moment on the machine can’t land on one version only:
# micro.py: nanoseconds per operation, best of 5 timeit repeats, as JSON
import json, sys, timeit
CASES = [
("call a Python function", "def f(): pass", "f()"),
("call a method", "class C:\n def m(self): pass\nc = C()", "c.m()"),
("read an attribute", "class C: pass\no = C(); o.x = 1", "o.x"),
("read a global, hot function", "G = 1\ndef g():\n for _ in range(1000): G\n", "g()"),
("add two small ints", "a = 1; b = 2", "a + b"),
("look up a dict key", "d = {'k': 1}", "d['k']"),
("call list()", "", "list()"),
("call range(10)", "", "range(10)"),
("call dict()", "", "dict()"),
("concatenate two strings", "s = 'abc'", "s + s"),
]
out = {}
for name, setup, stmt in CASES:
n = 200_000 if "hot function" not in name else 200
best = min(timeit.repeat(stmt, setup, repeat=5, number=n)) / n * 1e9
out[name] = best / 1000 if "hot function" in name else best
print(json.dumps(out))
The other three measurements are Part 14’s loop, Part 13’s program for three rounds, and start-up:
import time
def f(n):
total = 0
for i in range(n):
total += i * i % 7
return total
best = float("inf")
for _ in range(3):
t = time.perf_counter(); f(10_000_000); best = min(best, time.perf_counter() - t)
print(best)
# across.py: the same measurements on every version, alternating versions within each of three rounds
import json, subprocess, sys, time
VERSIONS = ["3.6.5", "3.7.0", "3.8.0", "3.9.1"]
py = lambda v: "/opt/py/f%s/bin/python3" % v
def wall(cmd, n):
best = float("inf")
for _ in range(n):
t = time.perf_counter(); subprocess.run(cmd, stdout=subprocess.DEVNULL); best = min(best, time.perf_counter() - t)
return best
results = {v: {} for v in VERSIONS}
for rnd in range(3):
for v in (VERSIONS if rnd % 2 == 0 else VERSIONS[::-1]):
r = json.loads(subprocess.run([py(v), "micro.py"], capture_output=True, text=True).stdout)
r["loop f(10M), s"] = float(subprocess.run([py(v), "loop.py"], capture_output=True, text=True).stdout)
r["slow.py 3 rounds, s"] = wall([py(v), "slow.py", "3"], 1)
r["start-up, ms"] = wall([py(v), "-c", "pass"], 10) * 1000
for k, x in r.items():
results[v][k] = min(results[v].get(k, float("inf")), x)
print(json.dumps(results, indent=1))
names = list(results[VERSIONS[0]])
print("%-30s" % "" + "".join("%10s" % v for v in VERSIONS))
for k in names:
unit = "ns" if "," not in k else ""
print("%-30s" % k + "".join("%10.2f" % results[v][k] for v in VERSIONS))
(slow.py is Part 13’s program unchanged, loop.py the loop above. across.py ran on Ubuntu 20.04’s own
Python 3.8.2, driving the four builds.)
$ python3 across.py | tail -14
3.6.5 3.7.0 3.8.0 3.9.1
call a Python function 21.62 19.51 19.31 18.61
call a method 30.32 23.94 23.53 23.03
read an attribute 10.41 10.29 10.32 10.56
read a global, hot function 5.66 6.21 6.03 6.22
add two small ints 7.02 7.15 7.22 8.12
look up a dict key 7.26 7.77 7.79 8.40
call list() 24.69 21.54 19.95 17.63
call range(10) 48.12 43.20 44.30 33.67
call dict() 32.44 33.11 32.51 27.88
concatenate two strings 15.04 15.56 16.09 16.30
loop f(10M), s 0.36 0.37 0.35 0.36
slow.py 3 rounds, s 0.96 0.94 1.36 1.37
start-up, ms 6.48 5.54 5.64 5.39
Units are nanoseconds unless the row says otherwise, and every nanosecond figure includes timeit’s own
loop, which is a few nanoseconds of the same bytecode on every version.
The same programs on four CPythons
Each row's bars are scaled to that row's 3.6.5 value. Shorter is faster.
Built with gcc 9.3 and no PGO or LTO, run alternately in one sitting, best of three rounds. Nanosecond rows include timeit's own loop. "Moved" marks rows whose fastest and slowest versions differ by 10% or more.
What moved is what the releases said would move. Method calls fell from 30.3 to 24.0 ns in 3.7, the
LOAD_METHOD and CALL_METHOD opcodes, new in 3.7, that skip creating a bound method object. Calling the
built-in types fell in 3.9, vectorcall. Start-up fell by a millisecond in 3.7. Function calls drifted down
by 14% across the four releases.
What didn’t move is as telling. The arithmetic loop, eleven bytecodes on small integers, costs the same in all four, 0.35 to 0.37 seconds: three and a half years of CPython releases did nothing for the code PyPy made 48 times faster in Part 14, because nothing in that loop’s path changed. Reading a global in a hot function is the same 6 ns, opcache or no, at this granularity. Adding two small integers and looking up a dict key came out a nanosecond slower on 3.9.1, in both of the two sittings I ran. That’s about the size of effect that a different layout of the eval loop in the compiled binary can produce, so I’d call it real for these builds and wouldn’t call it a regression in 3.9 without a profile-guided build to compare.
And slow.py, which was 0.94 seconds on 3.7.0 and 1.36 on 3.8.0.
Where 3.8 lost 44%
Part 13 found that program spending 60% of its time in the cycle collector, on 3.8.1. Splitting it into its three phases, with the collector on and off, on 3.7.0 and 3.8.0:
import gc, json, sys, time
def parse(lines):
return [line.split(",") for line in lines]
def score(rows):
total = 0
for row in rows:
for field in row:
total += len(field) * 31 % 7
return total
lines = ["alpha,beta,gamma,%d" % i for i in range(300000)]
if "nogc" in sys.argv:
gc.disable()
t = {"parse": 0.0, "score": 0.0, "report": 0.0}
for _ in range(3):
a = time.perf_counter(); rows = parse(lines)
b = time.perf_counter(); score(rows)
c = time.perf_counter(); json.dumps(rows)
d = time.perf_counter()
t["parse"] += b - a; t["score"] += c - b; t["report"] += d - c
print("%s %-5s parse %.3f score %.3f report %.3f collections %s" % (sys.version.split()[0], "nogc" if "nogc" in sys.argv else "gc",
t["parse"], t["score"], t["report"], [s["collections"] for s in gc.get_stats()]))
$ for v in 3.7.0 3.8.0; do /opt/py/f$v/bin/python3 phases.py; /opt/py/f$v/bin/python3 phases.py nogc; done
3.7.0 gc parse 0.549 score 0.147 report 0.207 collections [1183, 107, 8]
3.7.0 nogc parse 0.178 score 0.151 report 0.205 collections [14, 1, 0]
3.8.0 gc parse 0.941 score 0.145 report 0.214 collections [1182, 107, 8]
3.8.0 nogc parse 0.187 score 0.147 report 0.207 collections [13, 1, 0]
Without the collector, the two versions are the same in every phase. With it, score and report are
the same and parse, where three hundred thousand new lists a round set off collections, is 0.55 seconds
on 3.7.0 and 0.94 on 3.8.0. Both versions ran 1,183 or 1,182 collections, so 3.8 isn’t collecting more
often. Each collection takes about twice as long: about 0.37 seconds of collecting in total on 3.7.0,
about 0.75 on 3.8.0.
The one change to the collector’s data structures in 3.8 is bpo-33597, listed in 3.8’s “What’s New”
under optimisations: “Removed one Py_ssize_t member from PyGC_Head. All GC tracked objects (e.g.
tuple, list, dict) size is reduced 4 or 8 bytes.” In 3.7, each tracked object’s header had three words:
the two pointers of the doubly linked list from Part 4, and gc_refs, the scratch count that
subtract_refs decrements. In 3.8 it has two, and gc_refs is kept in the bits of the prev pointer
during a collection, with the list’s back links rebuilt afterwards and flag bits (NEXT_MASK_UNREACHABLE)
stored in the low bits of next. Every one of the three million lists in this program is eight bytes
smaller, and every collection does more work per object. I didn’t build 3.8 without that change, so this
is the likeliest explanation rather than a demonstrated one: it’s the only change to the collector that
3.8’s notes list. And it means part of what Part 13 measured, a collector taking 60%
of a program’s time, was 3.8’s: on 3.7 the same collector took about 40%.
It’s also an honest example of what performance work on CPython looks like. The memory saving is real and applies to every program, and the slowdown applies to programs that allocate millions of containers that survive, which is the case the collector was always worst at. Nobody wrote “the collector is slower” in a release note, because nobody measured this program.
The road to a faster CPython
This autumn brought more public plans for a faster CPython than the previous several years.
Mark Shannon’s plan. In October, Mark Shannon, who has worked on CPython’s internals for years,
published a plan on GitHub to make CPython about five times faster over four releases, in four stages of
about 50% each, since 1.5⁴ ≈ 5. As written: 3.10 gets “an adaptive, specializing interpreter”, one that
rewrites its own bytecode to fast paths for the types it actually sees, without generating machine code;
3.11 many smaller improvements, among them faster calls and returns through “better handling of frames”,
cheaper small integers and “zero overhead exception handling”; 3.12 and 3.13 a simple JIT compiler for
small regions, then larger ones. It comes with a second document, on funding, because the plan assumes
someone pays for the work. Stage one is the part that applies directly to this post’s table: the
eleven-bytecode loop above runs the same generic BINARY_MULTIPLY and INPLACE_ADD on every iteration
of every version, and specialising them for two small integers is the kind of change that would finally
move that row.
Pyston v2. Pyston, a JIT for Python started at Dropbox in 2014 and stopped there in 2017, came back on 28 October as Pyston v2, a performance-oriented fork of CPython 3.8 from some of its original developers, which means it keeps the C API and the extensions that depend on it. I couldn’t obtain the binary to measure it, so I’ll say no more than that.
HPy. Part 14 showed what the C API costs any engine that isn’t CPython: PyPy’s cpyext has to fake a
PyObject* for everything a C extension touches, with reference counts and a fixed layout. HPy, started
in 2019 by people from PyPy, CPython and other projects, is a new C API for extensions in which C holds
opaque handles rather than pointers into objects, so that an engine can move objects, skip reference
counting and use its own layout, and CPython can implement the same API with thin wrappers. It has no
release yet. If it succeeds, the thing that made every engine in Part 14 pay, CPython’s struct layout as
the definition of Python for C, becomes one implementation among several.
All three are bets on the same observation: most of CPython’s cost is not in any one operation but in being general on every one, checking types, boxing integers, allocating frames, counting references, every time, because the C has to handle every case. Every part of this series found that generality somewhere. Specialising, as PyPy does by tracing and as the plans propose by adapting, is how you stop paying for it.
Looking back
Each post in this series found one place where a Python program’s behaviour is explained by CPython’s C, and not by the language:
Sixteen places where Python turned out to be C
- 1objectsid() is an address; hash(-1) is -2 because C uses -1 for errors
- 2eval loopa global costs more than a local, because they are different opcodes
- 3eval loopdeep recursion overflows the C stack, not a Python one
- 4memorya forked child that only reads still copies pages, by touching refcounts
- 5memorydel doesn't return memory while one object pins an arena
- 6eval loopthreads don't run Python in parallel; Ctrl-C waits for C
- 7objectsone emoji makes a whole string four times bigger
- 8objectsone late attribute breaks key sharing and grows every instance
- 9objectsNumPy wraps where int grows; cost steps at digit boundaries
- 10C boundarya borrowed reference returned as new frees a list still in use
- 11C boundarya view pins its buffer; an mmap closed under NumPy segfaults
- 12eval loopthe global-read cache only switches on after 1,024 calls
- 13eval loopprofilers blame str.split for the cycle collector's time
- 14C boundaryone C call makes PyPy's own sum() 28 times slower
- 15processa same-size edit with the same mtime runs stale bytecode
- 16processa fork with a subinterpreter alive hangs the child
They fall into a few kinds. Some are the struct showing through: id() as an address, hash(-1),
strings that change width, dictionaries that share keys until they don’t, integers that are arrays of
digits. Some are the eval loop: locals as array slots and globals as dictionary lookups, recursion on
the C stack, the GIL, and caches that switch on only when a function is hot. Some are memory
management: reference counts written by readers, arenas pinned by one object, a collector that runs
inside whichever allocation crosses its threshold, and that a profiler then blames on that allocation.
Some are the process: what import does to the file system, what fork copies, what a subinterpreter
shares. And some are the C boundary, where the API is the struct and a borrowed reference, a view or a
PyList_GET_ITEM binds you to CPython’s representation of everything.
The thread through all of it is Part 1’s PyObject: a reference count and a type pointer at the start of
every value. Reference counting makes destruction deterministic and makes every read a write. The type
pointer makes everything dynamic and makes every operation a lookup. The C API exposes both, so C
extensions depend on both, so every faster engine has to emulate both. Most of what Python programmers
experience as Python’s performance, good and bad, is those two words of memory.
A note on the evidence
What I ran, and where. CPython 3.6.5, 3.7.0, 3.8.0 and 3.9.1 were built from their tags with Ubuntu
20.04’s gcc 9.3.0 and the default ./configure options (no PGO, no LTO, as in every part of this series),
in a chroot of 20.04 built with debootstrap from the release archive. Distribution packages of Python are
built with PGO and LTO and would be faster across the board; the comparisons here are between versions
built the same way, not of what any distribution ships. The chroot ran on a newer host kernel, and the
across.py run and the phase run each had the machine to themselves. Each script was extracted from this
page and run as shown, with outputs captured to files and pasted from them.
The numbers. across.py keeps the best of three rounds per measurement, each itself the best of
several repeats, so the table shows each version at its fastest in that sitting. Differences of a
nanosecond or two in the microbenchmarks, and of a few percent elsewhere, are within what one sitting can
show; the method-call, built-in-call, start-up and slow.py differences are well outside it, and
phases.py reproduced the slow.py result across four runs (3.8.0’s parse 0.92 to 1.21 s with the
collector, against 0.54 to 0.59 s on 3.7.0). A complete rerun of every command on this page, extracted
from the page, gave the same parser results, the same reimport counts and the same table within the
margins above, with every difference the post discusses in the same direction.
What I read rather than ran. The parser history and PEP 617’s own measurements are from the PEP; the
3.9 vectorcall conversions and PEP 573 from 3.9’s “What’s New”; bpo-33597’s description from 3.8’s “What’s
New” and Misc/NEWS.d/3.8.0a1.rst, and the header layouts from Include/objimpl.h at v3.7.0 and
Modules/gcmodule.c at v3.8.0. That the parenthesised with isn’t in 3.9’s language reference is from
the reference’s with statement grammar at v3.9.1. Mark Shannon’s plan is quoted from plan.md and
README.md in his faster-cpython repository as of 28 October. Pyston v2’s date and lineage are from
its announcement. HPy’s history is from its repository; it has no tagged release as of this writing.
What this series didn’t cover. Windows, by design. Async and the event loop, which are library more than runtime. The memory layout of frames and generators in detail. And every release after this one. Thank you for reading all seventeen.
Python 3.9 and the Road to a Faster CPython