← Writing

What Python 3.8 Changed Underneath

16 min readSystemsPythonCpythonCPerformanceC-Api
Contents

Python 3.8’s release notes say that LOAD_GLOBAL “is about 40% faster now”. On the same machine, in the same sitting, a function that reads a global eight times and is called a million times paid 0.47 nanoseconds per global read over a local in 3.8.0, against 2.05 in 3.7.5. A loop that does the same reads a million times inside one call paid 2.42 in 3.8.0, slightly more than in 3.7.5. Same instruction, same globals. The cache that speeds it up turns itself on only after the function has been called 1,024 times, and a hot loop inside a function that’s called once never gets it.

Most of what changed in 3.8, released two months ago, is like that: changes to the machinery rather than the language, each with conditions that the language doesn’t show. This post measures four of them against 3.7.5, the newest 3.7 release: the per-opcode cache, the call paths that the new vectorcall protocol formalises, the change to the ABI and its tag, and the new audit hooks. Then it embeds the interpreter with the new configuration API and finds that 3.8 linked differently.

This is Part 12 of a series on the CPython runtime. Part 2 measured LOAD_GLOBAL against LOAD_FAST in 3.6, and Part 10 measured calls across the C boundary in 3.7. It is written for Python programmers who have written a little C. Everything here ran on CPython 3.7.5 and 3.8.0, both built from their tags with Ubuntu 18.04’s gcc 7.3.0, alternated in one exclusive sitting so that their timings can be compared. The note at the end says exactly where and how.

A cache that waits to be asked twice

Part 2 found that a global read costs two dictionary lookups, globals then builtins, every time. 3.8 adds a per-instruction cache for LOAD_GLOBAL (bpo-26219, by Yury Selivanov and INADA Naoki). The first time an instruction finds its name, it records where, along with the version tags of the globals and builtins dicts. Every dict has had one since 3.6, a counter that changes whenever the dict does. On later executions, if both tags are unchanged, the instruction reads the value from the cache and skips both lookups. Part of TARGET(LOAD_GLOBAL) in 3.8’s Python/ceval.c:

                OPCACHE_CHECK();
                if (co_opcache != NULL && co_opcache->optimized > 0) {
                    _PyOpcache_LoadGlobal *lg = &co_opcache->u.lg;

                    if (lg->globals_ver ==
                            ((PyDictObject *)f->f_globals)->ma_version_tag
                        && lg->builtins_ver ==
                           ((PyDictObject *)f->f_builtins)->ma_version_tag)
                    {
                        PyObject *ptr = lg->ptr;
                        ...

The cache costs memory, a slot per instruction that uses it, so CPython doesn’t build it for every code object. It counts how many times each code object is entered, and builds the cache on the 1,024th:

#ifdef Py_DEBUG
// --with-pydebug is used to find memory leak.  opcache makes it harder.
// So we disable opcache when Py_DEBUG is defined.
// See bpo-37146
#define OPCACHE_MIN_RUNS 0  /* disable opcache */
#else
#define OPCACHE_MIN_RUNS 1024  /* create opcache when code executed this time */
#endif
...
    if (co->co_opcache_flag < OPCACHE_MIN_RUNS) {
        co->co_opcache_flag++;
        if (co->co_opcache_flag == OPCACHE_MIN_RUNS) {
            if (_PyCode_InitOpcache(co) < 0) {
                return NULL;
            }

This is at the top of _PyEval_EvalFrameDefault, so the count is of frames, of calls. A loop that runs a billion times inside one call is entered once. Measured, with the global read eight times per call (or per iteration) to make it visible, and the cost of the same code with a local subtracted:

import sys, timeit
G = 1

def eight_globals():                    # eight LOAD_GLOBALs per call
    return G + G + G + G + G + G + G + G

def eight_locals(g=1):                  # the same, with a local
    return g + g + g + g + g + g + g + g

def loop_globals(n):                    # eight per iteration, but only one call
    for _ in range(n):
        G + G + G + G + G + G + G + G

def loop_locals(n, g=1):
    for _ in range(n):
        g + g + g + g + g + g + g + g

N = 1000000
calls = (min(timeit.repeat(eight_globals, number=N, repeat=5)) - min(timeit.repeat(eight_locals, number=N, repeat=5))) / N / 8 * 1e9
loop = (min(timeit.repeat(lambda: loop_globals(N), number=1, repeat=5)) - min(timeit.repeat(lambda: loop_locals(N), number=1, repeat=5))) / N / 8 * 1e9
print("%d.%d.%d" % sys.version_info[:3], " extra ns per LOAD_GLOBAL: in a function called %d times %.2f,  in one long loop %.2f" % (N, calls, loop))
$ for round in 1 2 3; do for v in 3.7.5 3.8.0; do /opt/py/$v/bin/python3 opcache.py; done; done
3.7.5  extra ns per LOAD_GLOBAL: in a function called 1000000 times 2.14,  in one long loop 2.32
3.8.0  extra ns per LOAD_GLOBAL: in a function called 1000000 times 0.44,  in one long loop 3.00
3.7.5  extra ns per LOAD_GLOBAL: in a function called 1000000 times 2.05,  in one long loop 2.32
3.8.0  extra ns per LOAD_GLOBAL: in a function called 1000000 times 0.60,  in one long loop 2.42
3.7.5  extra ns per LOAD_GLOBAL: in a function called 1000000 times 1.55,  in one long loop 2.56
3.8.0  extra ns per LOAD_GLOBAL: in a function called 1000000 times 0.47,  in one long loop 2.42

In a function called a million times, a global read cost about 2 ns more than a local in 3.7.5 and about 0.5 ns more in 3.8.0: the cache removed three quarters of the difference. In one long loop it removed none, because loop_globals was entered five times (once per timeit repeat) and never reached 1,024. The release note’s “40% faster” is true of the instruction in code that’s called often, which is most code. It isn’t true of a script whose work is one big loop at module level or in main(), which is also common, and the difference is invisible in the source. Part 2’s advice to copy hot globals into locals still applies there.

What a global read costs over a local, 3.7.5 against 3.8.0

Nanoseconds per LOAD_GLOBAL, above the same code with LOAD_FAST. The cache is built for a code object on its 1,024th call.

3.7.53.8.0
in a function called a million timesthe cache is built and used
3.7.5 · 2.05 ns
3.8.0 · 0.47 ns
in one loop, inside one callentered 5 times: never cached
3.7.5 · 2.32 ns
3.8.0 · 2.42 ns

Hover or focus a bar for details.

Median of three alternating rounds. Same instruction, same globals: the only difference is how many times the function holding it was called.

Calls: vectorcall, and what didn’t move

3.8’s other headline internal change is vectorcall (PEP 590, by Jeroen Demeyer and Mark Shannon): a calling convention for any callable object, with the arguments passed as a C array plus a count, much like Part 10’s METH_FASTCALL, and a flag bit in the count for whether the callee may temporarily use the slot before the first argument. CPython already called Python functions and built-in functions this way internally. 3.8 formalises it as a slot that any type can implement, provisionally, with the aim of making it public in 3.9. What does that change for calls a program makes today?

import sys, timeit

def f(a, b=0):
    return a

class C:
    def m(self, a):
        return a

o, s, G = C(), "abc", 1

def load_global(n):
    for _ in range(n):
        G

def load_local(n):
    g = 1
    for _ in range(n):
        g

N = 1000000
cases = ["f(1, 2)", "f(1, b=2)", "o.m(1)", "len(s)", "max(1, 2)", "isinstance(o, C)", "C()", "dict(a=1)"]
base = min(timeit.repeat("pass", number=N, repeat=5)) / N * 1e9
row = {"python": "%d.%d.%d" % sys.version_info[:3]}
for stmt in cases:
    row[stmt] = min(timeit.repeat(stmt, globals=globals(), number=N, repeat=5)) / N * 1e9 - base
g = min(timeit.repeat(lambda: load_global(N), number=1, repeat=5)) / N * 1e9
l = min(timeit.repeat(lambda: load_local(N), number=1, repeat=5)) / N * 1e9
row["LOAD_GLOBAL (vs LOAD_FAST)"] = g - l
print(" ".join("%s=%.1f" % (k, v) if k != "python" else "python=%s" % v for k, v in row.items()))
$ for round in 1 2 3; do for v in 3.7.5 3.8.0; do /opt/py/$v/bin/python3 calls.py; done; done
python=3.7.5 f(1, 2)=21.4 f(1, b=2)=23.0 o.m(1)=21.8 len(s)=12.2 max(1, 2)=38.4 isinstance(o, C)=16.0 C()=20.1 dict(a=1)=49.3 LOAD_GLOBAL (vs LOAD_FAST)=2.7
python=3.8.0 f(1, 2)=22.8 f(1, b=2)=24.4 o.m(1)=22.1 len(s)=12.6 max(1, 2)=40.4 isinstance(o, C)=15.2 C()=19.9 dict(a=1)=55.8 LOAD_GLOBAL (vs LOAD_FAST)=3.0
python=3.7.5 f(1, 2)=21.2 f(1, b=2)=23.2 o.m(1)=23.1 len(s)=12.8 max(1, 2)=38.7 isinstance(o, C)=16.8 C()=20.0 dict(a=1)=48.7 LOAD_GLOBAL (vs LOAD_FAST)=2.7
python=3.8.0 f(1, 2)=21.5 f(1, b=2)=23.4 o.m(1)=22.8 len(s)=12.0 max(1, 2)=39.6 isinstance(o, C)=15.4 C()=19.6 dict(a=1)=55.5 LOAD_GLOBAL (vs LOAD_FAST)=3.0
python=3.7.5 f(1, 2)=21.0 f(1, b=2)=23.0 o.m(1)=21.8 len(s)=13.5 max(1, 2)=38.4 isinstance(o, C)=18.0 C()=21.3 dict(a=1)=48.9 LOAD_GLOBAL (vs LOAD_FAST)=3.4
python=3.8.0 f(1, 2)=22.9 f(1, b=2)=23.8 o.m(1)=21.7 len(s)=12.0 max(1, 2)=41.4 isinstance(o, C)=15.1 C()=20.0 dict(a=1)=55.9 LOAD_GLOBAL (vs LOAD_FAST)=3.0

Best of the three rounds for each, in nanoseconds per call above an empty statement:

Call3.7.53.8.0
f(1, 2)21.021.5
f(1, b=2)23.023.4
o.m(1)21.821.7
len(s)12.212.0
max(1, 2)38.439.6
isinstance(o, C)16.015.1
C()20.019.6
dict(a=1)48.755.5
LOAD_GLOBAL (vs LOAD_FAST)2.73.0

Most calls cost the same within a nanosecond, which is the noise of these measurements. isinstance is about 6% cheaper in 3.8, from the faster argument handling for some built-ins that the release notes mention. dict(a=1) is 14% more expensive, and max(1, 2) 3%. The LOAD_GLOBAL row is the long-loop case from above: no cache, so no gain. So vectorcall made these calls no faster. It wasn’t meant to: Python functions, methods and built-ins already took the fast paths it formalises. What it changes is that a C extension’s own callable types can take them too, and that tools that make their own callables, such as Cython’s functions, can be called as cheaply as built-ins. That’s a change to what’s possible from C, which these Python-level timings can’t show.

A release can be faster on its benchmark suite and not on yours. A microbenchmark of the operations a program actually uses, run on both versions in one sitting, is the only way to know.

An ABI tag that lost its letter

import sys, sysconfig
print("%d.%d.%d" % sys.version_info[:3], " abiflags=%r" % sys.abiflags,
      " EXT_SUFFIX=%s" % sysconfig.get_config_var("EXT_SUFFIX"))
$ for v in 3.7.5 3.8.0; do /opt/py/$v/bin/python3 abi.py; done
3.7.5  abiflags='m'  EXT_SUFFIX=.cpython-37m-x86_64-linux-gnu.so
3.8.0  abiflags=''  EXT_SUFFIX=.cpython-38-x86_64-linux-gnu.so

Part 10’s extension was spam.cpython-37m-x86_64-linux-gnu.so. In 3.8 the same build is spam.cpython-38-x86_64-linux-gnu.so. The m meant “built with pymalloc”, and it was in the tag because extensions built with and without pymalloc used to be incompatible. They no longer are, so 3.8 dropped it, and with it the python3.8m executable and python3.8m-config script. The other ABI change goes deeper. Until 3.7, a debug build (--with-pydebug) defined Py_TRACE_REFS, which adds two pointers to every object’s header for a list of all live objects: Part 1’s _PyObject_HEAD_EXTRA. Every struct offset changed, so release-built extensions couldn’t load in a debug interpreter. In 3.8 debug builds no longer imply it (it has its own configure flag, --with-trace-refs), and release extensions load in debug interpreters. The 3.8 release notes call it “the only ABI incompatibility” between them.

Both changes are invisible to Python code and decide whether a compiled wheel loads. Installers match wheel tags against them, and a wheel tagged cp37m won’t be offered to 3.8, which is why every package with C code had to publish new wheels for 3.8, as NumPy did with 1.17.3 in Part 11.

Audit hooks: watching the interpreter

PEP 578 adds audit hooks: callbacks that the interpreter calls, with an event name and arguments, whenever it does something security-relevant. Opening a file, importing a module, compiling or executing code, creating a socket and dozens of other operations raise events. A hook can log them, and it can block one by raising an exception. Hooks added with sys.addaudithook can’t be removed, which is the point: code loaded later can’t switch them off.

import collections, sys, time

events = []
def hook(event, args):
    events.append(event)
sys.addaudithook(hook)                   # cannot be removed for the rest of the process

import json                              # already imported by nothing here: a real import
with open(__file__) as f:
    f.read()
compile("1 + 1", "<string>", "eval")
exec("x = 1")
import socket
socket.socket().close()

counts = collections.Counter(events)
print(len(events), "audit events, by kind:")
for name, n in counts.most_common():
    print("  %-22s %d" % (name, n))
$ python3 audit.py
94 audit events, by kind:
  open                   33
  import                 28
  exec                   19
  compile                4
  object.__setattr__     3
  os.listdir             2
  object.__getattr__     2
  sys._getframe          2
  socket.__new__         1

94 audit events from six lines of code

Python 3.8.0: two imports, a file read, a compile, an exec and a socket, counted by event name.

open
33
import
28
exec
19
compile
4
object.__setattr__
3
os.listdir
2
object.__getattr__
2
sys._getframe
2
socket.__new__
1

Most of them are the import system at work: each imported module raises an import event, each file it reads an open, and each module body it runs an exec.

Six lines of ordinary code raised 94 events. Most come from import json and import socket: every module imported raises an import event, every file the import system opens to find and read a module raises open, and every module body it runs raises exec. That’s 28 imports for two import statements, because each module imports others. The os.listdir events are the import system reading directories, and sys._getframe and the object.__getattr__/__setattr__ events come from the standard library modules that were run. An audit hook is a view of the interpreter’s own activity that nothing before 3.8 gave from inside Python: what a library really opens and imports, as it happens.

The cost is a check per event when no hook is installed, and a call into Python per event when one is:

import sys, timeit

def cycle():
    with open(__file__, "rb") as f:
        f.read(1)

N = 20000
before = min(timeit.repeat(cycle, number=N, repeat=5)) / N * 1e6
sys.addaudithook(lambda event, args: None)
after = min(timeit.repeat(cycle, number=N, repeat=5)) / N * 1e6
print("open + read + close: %.2f us without a hook, %.2f us with one empty Python hook" % (before, after))
$ python3 auditcost.py
open + read + close: 1.89 us without a hook, 1.98 us with one empty Python hook

About 0.1 µs per event for an empty Python hook, small next to a system call. A hook that logs every event to a file would cost much more. The hooks are meant for monitoring and policy, and the PEP is explicit that they aren’t a sandbox: Python code with access to ctypes can reach under them, as it reached under the small-int cache in Part 1.

Embedding: a new configuration API, and a new linker flag

Part 1 embedded the interpreter in a C program with Py_Initialize(). Configuring an embedded interpreter used to mean setting global variables and environment variables before that call. PEP 587 (by Victor Stinner) replaces them with a PyConfig structure, initialised in one of two modes. Python configuration behaves like the python program, reading environment variables and the command line. Isolated configuration ignores both, which an application embedding Python usually wants:

#define PY_SSIZE_T_CLEAN
#include <Python.h>

int main(int argc, char **argv)
{
    PyConfig config;
    PyConfig_InitIsolatedConfig(&config);        /* ignore environment and user site */
    config.optimization_level = 2;               /* like python -OO */
    PyStatus status = PyConfig_SetString(&config, &config.program_name, L"embedded");
    if (!PyStatus_Exception(status))
        status = Py_InitializeFromConfig(&config);
    PyConfig_Clear(&config);
    if (PyStatus_Exception(status))
        Py_ExitStatusException(status);

    PyRun_SimpleString(
        "import sys\n"
        "print('isolated', sys.flags.isolated, ' optimize', sys.flags.optimize,"
        " ' ignore_environment', sys.flags.ignore_environment)\n"
        "print('sys.path[0] =', sys.path[0])\n");
    Py_Finalize();
    return 0;
}

Built the way Part 1 built its embedding program, it doesn’t link:

$ gcc -o embed embed.c $(python3-config --cflags) $(python3-config --ldflags)
/tmp/ccJpM7VS.o: In function `main':
/work/x12/embed.c:7: undefined reference to `PyConfig_InitIsolatedConfig'
/work/x12/embed.c:9: undefined reference to `PyConfig_SetString'
/work/x12/embed.c:10: undefined reference to `PyStatus_Exception'
/work/x12/embed.c:12: undefined reference to `PyConfig_Clear'
/work/x12/embed.c:13: undefined reference to `PyStatus_Exception'
/work/x12/embed.c:16: undefined reference to `PyRun_SimpleStringFlags'
/work/x12/embed.c:21: undefined reference to `Py_Finalize'
/work/x12/embed.c:11: undefined reference to `Py_InitializeFromConfig'
/work/x12/embed.c:14: undefined reference to `Py_ExitStatusException'
collect2: error: ld returned 1 exit status
$ gcc -o embed embed.c $(python3-config --cflags) $(python3-config --ldflags --embed) -no-pie
$ PYTHONOPTIMIZE=0 PYTHONPATH=/nowhere ./embed
isolated 1  optimize 2  ignore_environment 1
sys.path[0] = /opt/py/3.8.0/lib/python38.zip

In 3.8, python3-config --ldflags no longer includes -lpython3.8. Extension modules must not link against libpython (the interpreter that loads them already contains it), and the old flags, which included it, were wrong for them. Programs that embed Python now ask for it with the new --embed option. With it, the program links and runs, and the isolated configuration did what it says: isolated and ignore_environment are 1, the optimisation level is the 2 set in C even though the environment says PYTHONOPTIMIZE=0, and PYTHONPATH=/nowhere didn’t make it into sys.path. A 3.7-era build script for an embedding application fails on 3.8 at link time, with errors about missing symbols that have nothing to do with the change.

What we covered

  • 3.8’s LOAD_GLOBAL cache cut the extra cost of a global read from about 2 ns to 0.5 ns, in functions entered at least 1,024 times, the threshold for building a code object’s cache. A long loop in a function called once got nothing.
  • Vectorcall (PEP 590) formalises the fast calling path for any C type. Calls from Python cost the same in 3.7.5 and 3.8.0 within a nanosecond, except isinstance (6% faster) and dict(a=1) (14% slower).
  • sys.abiflags lost the m (pymalloc no longer changes the ABI), and debug builds no longer change object layouts, so release extensions load in them.
  • Audit hooks (PEP 578) reported 94 events for two imports, a file, a compile, an exec and a socket, at about 0.1 µs per event for an empty hook.
  • PyConfig (PEP 587) configures an embedded interpreter in one structure, and embedding now needs python3-config --ldflags --embed.

The next post looks at the tools that watch a running program from outside: profilers, debuggers and tracers, what each one sees of CPython’s C and Python stacks, and what each costs.

A note on the evidence

What I ran, and where. Everything ran on CPython 3.7.5 and 3.8.0, both built from their tags with Ubuntu 18.04’s gcc 7.3.0 and configure’s default flags, on a minimal 18.04 userland from the release archive, as a chroot on a 64-bit x86 machine. 3.7.5 came out the day after 3.8.0, and was the newest 3.7 when this was written. The comparisons alternated the two interpreters for three rounds, in one sitting, with nothing else running. Each script was extracted from this page and run as shown, with outputs captured to files and pasted from them; the linker’s output is from that rerun.

The numbers. The opcache figures are the median of three rounds, and the call table is the best round for each. The rounds disagree by up to a nanosecond, which is the size of most of the differences in the table, so only the LOAD_GLOBAL cache, isinstance and dict(a=1) are differences I’d stand behind. These builds use no profile-guided or link-time optimisation, so distributions’ own builds of 3.7 and 3.8 will show other absolute numbers, and possibly other small differences.

What I worked out rather than read. That loop_globals never got the cache follows from OPCACHE_MIN_RUNS and from its being entered five times. I didn’t print co_opcache_flag. What each of the 94 audit events was caused by is inferred from their names and the code that ran.

What I cited rather than ran. The C quoted is from Python/ceval.c at v3.8.0. The other changes are from 3.8’s “What’s New” and the PEPs: PEP 590 (vectorcall, “currently provisional”), PEP 578, PEP 587, bpo-26219 (“about 40% faster”), bpo-36707 (the m flag) and bpo-36465 (debug-build ABI). The --embed change is from the same document’s porting notes.

What I’d still change. These are microbenchmarks of single operations. The project’s own benchmark suite, pyperformance, would say how the changes add up on real programs. And an extension type that implements vectorcall itself, compared with the same type without it, would show the change PEP 590 is actually about, which no timing from Python code can.

More