← Writing

The Loop That Runs Your Bytecode

Contents

On Ubuntu 18.04, a five-line Python function that adds up a list compiles to 30 bytes: fifteen instructions of two bytes each. Running it means one C function, _PyEval_EvalFrameDefault, reading those bytes two at a time and jumping, through a table of 256 addresses inside itself, to the C code for each instruction. On the machine I measured, reading a local variable added 0.6 nanoseconds to each pass of a loop. Reading a global cost five times as much, and fetching a method cost seventeen times as much. A debugger’s trace hook made the whole loop nine times slower.

None of that is in the language. It is how one interpreter, written in C, executes it. This post follows one function from source text to code object to bytecode, then watches the interpreter’s loop run it, one push and pop at a time. Then it measures what that loop’s design costs, and looks at the places where the cost leaks into how people write Python.

This is Part 2 of a series on the CPython runtime. Part 1 showed what a Python value is in memory, and this one runs code on those values. It is written for Python programmers who have written a little C. Everything here ran on Ubuntu 18.04’s release packages: python3 3.6.5-3, its debug build python3-dbg, and gdb 8.1. Two extra interpreters were built from the 3.6.5 source with the same gcc 7.3.0 to compare two ways of dispatching. The note at the end says exactly what ran where.

One function, four forms

Here is the function this post follows, in a file called total.py:

def total(xs):
    s = 0
    for x in xs:
        s += x
    return s

Before CPython runs a line of it, the text passes through four stages, each a separate piece of C:

  1. Tokens. Parser/tokenizer.c cuts the text into names, numbers, operators, and the INDENT/DEDENT tokens that make indentation significant.
  2. A parse tree, then an AST. A parser generated from the grammar in Grammar/Grammar builds a concrete parse tree, and Python/ast.c turns it into an abstract syntax tree: the program’s structure, without the punctuation.
  3. A symbol table. Python/symtable.c decides, for every name in every function, whether it is local, global, or a free variable of an enclosing function. This is where s and x become locals, decided once, at compile time.
  4. A code object. Python/compile.c walks the AST and emits bytecode, and Python/peephole.c tidies it up. The result is a PyCodeObject: the bytecode plus the tables it refers to.

The standard library exposes each stage, so you can look at all four:

import ast, dis, io, tokenize

source = open("total.py").read()

print("--- tokens (first line)")
for tok in tokenize.generate_tokens(io.StringIO(source).readline):
    if tok.start[0] > 1:
        break
    print("%-10s %r" % (tokenize.tok_name[tok.type], tok.string))

print("--- AST")
print(ast.dump(ast.parse(source).body[0].body[1]))

module = compile(source, "total.py", "exec")
code = module.co_consts[0]
print("--- the code object")
for name in ("co_name", "co_argcount", "co_nlocals", "co_varnames", "co_consts",
             "co_names", "co_stacksize", "co_flags"):
    print("%-12s %r" % (name, getattr(code, name)))
print("co_code      %d bytes: %s" % (len(code.co_code), code.co_code.hex()))
$ python3 stages.py
--- tokens (first line)
NAME       'def'
NAME       'total'
OP         '('
NAME       'xs'
OP         ')'
OP         ':'
NEWLINE    '\n'
--- AST
For(target=Name(id='x', ctx=Store()), iter=Name(id='xs', ctx=Load()), body=[AugAssign(target=Name(id='s', ctx=Store()), op=Add(), value=Name(id='x', ctx=Load()))], orelse=[])
--- the code object
co_name      'total'
co_argcount  1
co_nlocals   3
co_varnames  ('xs', 's', 'x')
co_consts    (None, 0)
co_names     ()
co_stacksize 3
co_flags     67
co_code      30 bytes: 64017d0178147c0044005d0c7d027c017c0237007d01710a57007c015300

(tokenize here is the pure-Python tokenizer in the standard library, not the C one the compiler uses, but the two agree on what the tokens are.)

Compiling total.py as a module produces a code object for the module, and the function’s code object is one of the module’s constants: a def statement, when it runs, wraps that constant in a new function object. The function’s code object holds everything the interpreter needs:

  • co_varnames lists the locals, arguments first: xs, s, x. From now on they are numbers, 0, 1 and 2, because the symbol table already knows that nothing else can create a local in this function.
  • co_consts holds the constants the bytecode refers to by index: None and 0. None is there because every code object gets it, whether or not the code uses it.
  • co_names holds global and attribute names, and is empty because total uses neither.
  • co_stacksize is 3: the compiler worked out that this code never has more than three values on its evaluation stack at once, so the interpreter can allocate exactly that much.
  • co_flags 67 is 0x43: CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE. Locals live in an array instead of a dict, each call gets fresh locals, and nothing is captured from an enclosing function.
  • co_code is the program: 30 bytes.

Two bytes per instruction

Since Python 3.6, every instruction is exactly two bytes: an opcode and an argument. (Before 3.6, instructions with no argument took one byte and the rest took three. The change is called wordcode.) The dis module knows the names of the opcodes, so the 30 bytes can be decoded by hand:

import dis
exec(open("total.py").read())
code = total.__code__.co_code

for offset in range(0, len(code), 2):
    op, arg = code[offset], code[offset + 1]
    print("%2d: %02x %02x   %-14s %s" % (offset, op, arg, dis.opname[op],
                                         arg if op >= dis.HAVE_ARGUMENT else ""))
print()
dis.dis(total)
$ python3 decode.py
 0: 64 01   LOAD_CONST     1
 2: 7d 01   STORE_FAST     1
 4: 78 14   SETUP_LOOP     20
 6: 7c 00   LOAD_FAST      0
 8: 44 00   GET_ITER       
10: 5d 0c   FOR_ITER       12
12: 7d 02   STORE_FAST     2
14: 7c 01   LOAD_FAST      1
16: 7c 02   LOAD_FAST      2
18: 37 00   INPLACE_ADD    
20: 7d 01   STORE_FAST     1
22: 71 0a   JUMP_ABSOLUTE  10
24: 57 00   POP_BLOCK      
26: 7c 01   LOAD_FAST      1
28: 53 00   RETURN_VALUE   

  2           0 LOAD_CONST               1 (0)
              2 STORE_FAST               1 (s)

  3           4 SETUP_LOOP              20 (to 26)
              6 LOAD_FAST                0 (xs)
              8 GET_ITER
        >>   10 FOR_ITER                12 (to 24)
             12 STORE_FAST               2 (x)

  4          14 LOAD_FAST                1 (s)
             16 LOAD_FAST                2 (x)
             18 INPLACE_ADD
             20 STORE_FAST               1 (s)
             22 JUMP_ABSOLUTE           10
        >>   24 POP_BLOCK

  5     >>   26 LOAD_FAST                1 (s)
             28 RETURN_VALUE

My decoder and dis agree byte for byte, which is the point: there’s no hidden structure. Opcode 0x64 (100) is LOAD_CONST, and its argument 1 is an index into co_consts, so it means “push the constant 0”. 0x7d (125) is STORE_FAST, whose argument indexes the locals array. The opcodes below dis.HAVE_ARGUMENT (90) take no argument, and their second byte is a padding zero: GET_ITER is 44 00. Jump arguments are byte offsets. FOR_ITER 12 jumps 12 bytes past the next instruction, to 24, when the iterator is exhausted, and JUMP_ABSOLUTE 10 goes back to the FOR_ITER. SETUP_LOOP pushes a block onto a separate block stack, so that break knows where to go, and POP_BLOCK removes it.

Two more details complete the format. An argument bigger than 255 is built from EXTENDED_ARG prefixes, each contributing eight more bits, so a function with 300 constants has a few four-byte instructions. The line numbers on the left of dis’s listing are not in co_code at all. They’re recovered from co_lnotab, a compressed table of (bytecode offset, line) increments, and only when something asks: a traceback, a debugger, or dis itself.

The loop

The interpreter for all of this is one C function in Python/ceval.c, _PyEval_EvalFrameDefault, almost 3,000 lines long. Strip away the error handling and it is a loop around a switch, with a check at the top:

    for (;;) {
        ...
        /* Do periodic things.  Doing this every time through
           the loop would add too much overhead, so we do it
           only every Nth instruction.  We also do it if
           ``pendingcalls_to_do'' is set, i.e. when an asynchronous
           event needs attention (e.g. a signal handler or
           async I/O handler); see Py_AddPendingCall() and
           Py_MakePendingCalls() above. */

        if (_Py_atomic_load_relaxed(&eval_breaker)) {
            ... run pending calls, let another thread take the GIL, raise async exceptions ...
        }

    fast_next_opcode:
        f->f_lasti = INSTR_OFFSET();
        ... line tracing, if a trace function is set ...

        /* Extract opcode and argument */

        NEXTOPARG();
    dispatch_opcode:
        ...
        switch (opcode) {

        TARGET(LOAD_FAST) {
            PyObject *value = GETLOCAL(oparg);
            if (value == NULL) {
                format_exc_check_arg(PyExc_UnboundLocalError,
                                     UNBOUNDLOCAL_ERROR_MSG,
                                     PyTuple_GetItem(co->co_varnames, oparg));
                goto error;
            }
            Py_INCREF(value);
            PUSH(value);
            FAST_DISPATCH();
        }

        PREDICTED(LOAD_CONST);
        TARGET(LOAD_CONST) {
            PyObject *value = GETITEM(consts, oparg);
            Py_INCREF(value);
            PUSH(value);
            FAST_DISPATCH();
        }

        PREDICTED(STORE_FAST);
        TARGET(STORE_FAST) {
            PyObject *value = POP();
            SETLOCAL(oparg, value);
            FAST_DISPATCH();
        }
        ...

(The comment about “every Nth instruction” is older than the code under it: since Python 3.2 the check is a single flag, eval_breaker, that other threads and signal handlers set when something needs attention.)

NEXTOPARG reads the next two-byte code unit and splits it:

#define NEXTOPARG()  do { \
        _Py_CODEUNIT word = *next_instr; \
        opcode = _Py_OPCODE(word); \
        oparg = _Py_OPARG(word); \
        next_instr++; \
    } while (0)

and the stack is nothing more than a C array of PyObject * and a pointer into it:

#define TOP()             (stack_pointer[-1])
#define SECOND()          (stack_pointer[-2])
#define SET_TOP(v)        (stack_pointer[-1] = (v))
#define BASIC_PUSH(v)     (*stack_pointer++ = (v))
#define BASIC_POP()       (*--stack_pointer)
...
#define GETLOCAL(i)     (fastlocals[i])

So LOAD_FAST 2 is “take element 2 of the locals array, add one to its reference count, store it at the stack pointer and move the pointer up”. In C that’s an array index, an increment and a store. The name x doesn’t exist at run time. It became the number 2 in the symbol table, and only co_varnames remembers it, for error messages and debuggers. The if (value == NULL) check is how an UnboundLocalError happens: a local slot that was never assigned holds a NULL pointer.

Where do fastlocals and the stack live? In the frame. Every call creates a PyFrameObject, defined in Include/frameobject.h, and its last field is a variable-length array:

typedef struct _frame {
    PyObject_VAR_HEAD
    struct _frame *f_back;      /* previous frame, or NULL */
    PyCodeObject *f_code;       /* code segment */
    PyObject *f_builtins;       /* builtin symbol table (PyDictObject) */
    PyObject *f_globals;        /* global symbol table (PyDictObject) */
    PyObject *f_locals;         /* local symbol table (any mapping) */
    PyObject **f_valuestack;    /* points after the last local */
    ...
    int f_lasti;                /* Last instruction if called */
    ...
    PyObject *f_localsplus[1];  /* locals+stack, dynamically sized */
} PyFrameObject;

f_localsplus holds the locals and then, directly after them, the evaluation stack: co_nlocals + co_stacksize pointers in one block, with f_valuestack pointing at the first stack slot. For total that is 3 locals and 3 stack slots. f_back links each frame to its caller’s, which is the call stack a traceback prints. f_lasti is the offset of the instruction being executed, which the loop stores before every instruction, and which Python can read:

import sys

def where():
    f = sys._getframe()
    return f.f_lasti, f.f_code.co_name, f.f_back.f_code.co_name

def show():
    print("lasti in where():", where())
    print("lasti in show(): ", sys._getframe().f_lasti)
    print("lasti in show(): ", sys._getframe().f_lasti)

show()

def deep(a, b, c, d, e, f, g, h):
    x = y = z = 0
    return sys._getframe()
fr = deep(*range(8))
print("frame of deep():", sys.getsizeof(fr), "bytes; co_nlocals =", fr.f_code.co_nlocals,
      "co_stacksize =", fr.f_code.co_stacksize)
print("f_back of deep()'s frame:", fr.f_back.f_code.co_name, "  f_lasti:", fr.f_lasti)
$ python3 frames.py
lasti in where(): (10, 'where', 'show')
lasti in show():  22
lasti in show():  38
frame of deep(): 504 bytes; co_nlocals = 11 co_stacksize = 2
f_back of deep()'s frame: <module>   f_lasti: 18

The two show() lines print different numbers because they’re different instructions. In each, the frame’s f_lasti is read by the LOAD_ATTR f_lasti instruction, at offsets 22 and 38 of show’s bytecode. The program can see its own program counter. deep()’s frame is 504 bytes: the fixed part of a PyFrameObject (384 bytes, including a 20-entry block stack), 13 pointers for 11 locals and a 2-deep stack (one is already counted in the fixed part), and the 24-byte GC header from Part 1. Frames are allocated on the heap, not on the C stack. That’s why fr is still a perfectly good object after deep() returned, with its caller and its last instruction intact.

Watching it run

Ubuntu’s python3-dbg package is CPython built with --with-pydebug, and a debug build compiles in a feature that the release build leaves out: low-level tracing. If a module’s globals contain the name __ltrace__, every frame that starts running prints each instruction it executes and every value pushed or popped. The check in ceval.c is one line:

#ifdef LLTRACE
    lltrace = _PyDict_GetItemId(f->f_globals, &PyId___ltrace__) != NULL;
#endif

So:

__ltrace__ = 1           # any value: ceval.c only checks that the name exists in globals

def total(xs):
    s = 0
    for x in xs:
        s += x
    return s

total([10, 20, 30])
$ python3-dbg lltrace.py
0: 100, 1
push 0
2: 125, 1
pop 0
4: 120, 20
6: 124, 0
push [10, 20, 30]
8: 68
10: 93, 12
push 10
12: 125, 2
pop 10
14: 124, 1
push 0
16: 124, 2
push 10
18: 55
pop 10
20: 125, 1
pop 10
22: 113, 10
10: 93, 12
push 20
...
22: 113, 10
10: 93, 12
stackadj 30
24: 87
26: 124, 1
push 60
28: 83
pop 60
ext_pop [10, 20, 30]
ext_pop <function total at 0x7d6417797d48>
push 60
24: 1
pop 60
26: 100, 6
push None
28: 83
pop None

Each offset: opcode, argument line is one trip through the loop, printed in decimal, so 0: 100, 1 is LOAD_CONST 1 at offset 0 and 18: 55 is INPLACE_ADD. The push and pop lines come from the PUSH and POP macros, which in a debug build call a printing function. The trace is the interpreter’s own account of what it did, not a reconstruction.

Read the first pass of the loop in order. LOAD_CONST pushes 0 and STORE_FAST pops it into s. LOAD_FAST 0 pushes the list. GET_ITER replaces the top of the stack with an iterator, but does it with SET_TOP, which the debug build doesn’t trace, so it prints nothing. FOR_ITER calls the iterator’s C tp_iternext and pushes 10, which STORE_FAST 2 pops into x. Then s += x is four instructions: push s (0), push x (10), INPLACE_ADD, which pops one operand and overwrites the other with the sum (again by SET_TOP, so only one pop shows), and STORE_FAST 1, which pops the sum, 10, into s. JUMP_ABSOLUTE goes back to offset 10. In all, each pass of the loop is seven instructions and six pushes or pops, for one addition.

The figure below replays the whole trace. The stack and the locals it shows are rebuilt from the traced pushes and pops alone, plus the two untraced SET_TOPs.

The loop running total([10, 20, 30])

Every instruction the interpreter executed, with the lines its debug build printed. The stack grows upwards; locals are slots 0, 1 and 2 of the frame.

0 LOAD_CONST 0
2 STORE_FAST s
4 SETUP_LOOP to 26
6 LOAD_FAST xs
8 GET_ITER
10 FOR_ITER to 24
12 STORE_FAST x
14 LOAD_FAST s
16 LOAD_FAST x
18 INPLACE_ADD
20 STORE_FAST s
22 JUMP_ABSOLUTE to 10
24 POP_BLOCK
26 LOAD_FAST s
28 RETURN_VALUE

What the interpreter printed

Value stack

Locals (f_localsplus)

0: LOAD_CONST 0 push 0 2: STORE_FAST s pop 0 4: SETUP_LOOP to 26 6: LOAD_FAST xs push [10, 20, 30] 8: GET_ITER 10: FOR_ITER to 24 push 10 12: STORE_FAST x pop 10 14: LOAD_FAST s push 0 16: LOAD_FAST x push 10 18: INPLACE_ADD pop 10 20: STORE_FAST s pop 10 22: JUMP_ABSOLUTE to 10 10: FOR_ITER to 24 push 20 12: STORE_FAST x pop 20 14: LOAD_FAST s push 10 16: LOAD_FAST x push 20 18: INPLACE_ADD pop 20 20: STORE_FAST s pop 30 22: JUMP_ABSOLUTE to 10 10: FOR_ITER to 24 push 30 12: STORE_FAST x pop 30 14: LOAD_FAST s push 30 16: LOAD_FAST x push 30 18: INPLACE_ADD pop 30 20: STORE_FAST s pop 60 22: JUMP_ABSOLUTE to 10 10: FOR_ITER to 24 stackadj 30 24: POP_BLOCK 26: LOAD_FAST s push 60 28: RETURN_VALUE pop 60

Thirty instructions for three additions: each pass of the loop is seven of them. Values on the stack are pointers to objects; the figure prints the objects' repr, as the debug build does.

Two lines near the end of the trace show C showing through even here.

stackadj 30. When FOR_ITER finds the iterator exhausted, it drops the iterator with STACKADJ(-1), and the debug build prints TOP() after the adjustment. But the stack is now empty, so TOP(), which is stack_pointer[-1], reads the slot just below the stack. Because the stack follows the locals in f_localsplus, that slot is the last local, x, which holds 30. The trace printed a variable it was never asked about, by reading one element before the start of an array. It’s harmless here, because it only reads a slot inside the same allocation, but it shows the locals and the stack sitting side by side in one array.

The lines after RETURN_VALUE. RETURN_VALUE pops 60 and leaves total’s frame. But the trace keeps going, because lltrace is not a property of the frame. It is a C static int, one variable for the whole interpreter, set from the globals of each frame that starts. The module’s frame was already running when __ltrace__ = 1 executed, so it didn’t trace at first. Once total set the static to 1 and returned, the module’s frame went on tracing: the ext_pop lines are its call machinery dropping the function and its argument, and then come its last three instructions, which discard the result and return None. The debug feature has the same kind of global state that causes bugs in ordinary programs.

256 addresses inside one function

switch (opcode) with about 120 cases is how the loop is written. It is not quite how this build dispatches. Look at how TARGET and FAST_DISPATCH are defined when USE_COMPUTED_GOTOS is on:

#if USE_COMPUTED_GOTOS
/* Import the static jump table */
#include "opcode_targets.h"

#define TARGET(op) \
    TARGET_##op: \
    case op:

#define DISPATCH() \
    { \
        if (!_Py_atomic_load_relaxed(&eval_breaker)) {      \
                    FAST_DISPATCH(); \
        } \
        continue; \
    }
...
#define FAST_DISPATCH() \
    { \
        if (!_Py_TracingPossible && !PyDTrace_LINE_ENABLED()) { \
            f->f_lasti = INSTR_OFFSET(); \
            NEXTOPARG(); \
            goto *opcode_targets[opcode]; \
        } \
        goto fast_next_opcode; \
    }

Every opcode body begins with a C label as well as a case, and every body ends by fetching the next instruction itself and jumping straight to the next body through opcode_targets, an array of 256 label addresses. goto *expr and &&label are a GCC extension called “labels as values”, and opcode_targets.h is generated from the opcode list:

static void *opcode_targets[256] = {
    &&_unknown_opcode,
    &&TARGET_POP_TOP,
    &&TARGET_ROT_TWO,
    ...

Ubuntu’s interpreter was configured with --with-computed-gotos (you can see it in sysconfig.get_config_var("CONFIG_ARGS")). Its debug symbols ship in python3-dbg, so gdb can show the table, from inside the function where it is declared:

$ gdb -batch -ex 'set pagination off' -ex 'break _PyEval_EvalFrameDefault' -ex 'run -S -c pass' \
    -ex 'print opcode_targets[124]' -ex 'print opcode_targets[100]' -ex 'print opcode_targets[55]' \
    -ex 'print opcode_targets[0]' -ex 'print sizeof(opcode_targets)/sizeof(opcode_targets[0])' \
    -ex 'info line *opcode_targets[124]' --args /usr/bin/python3.6

Breakpoint 1, _PyEval_EvalFrameDefault (f=Frame 0x7ffff7e11200, for file <frozen importlib._bootstrap>, line 8, in <module> (), throwflag=0) at ../Python/ceval.c:758
758	../Python/ceval.c: No such file or directory.
$1 = (void *) 0x553c30 <_PyEval_EvalFrameDefault+11152>
$2 = (void *) 0x552293 <_PyEval_EvalFrameDefault+4595>
$3 = (void *) 0x553f08 <_PyEval_EvalFrameDefault+11880>
$4 = (void *) 0x555f19 <_PyEval_EvalFrameDefault+20089>
$5 = 256
Line 1277 of "../Python/ceval.c" starts at address 0x553c30 <_PyEval_EvalFrameDefault+11152> and ends at 0x553c3c <_PyEval_EvalFrameDefault+11164>.

Entry 124 (LOAD_FAST) is the address 11,152 bytes into _PyEval_EvalFrameDefault, and gdb maps it to line 1277 of ceval.c, the first line of the LOAD_FAST body. Entries 100 (LOAD_CONST) and 55 (INPLACE_ADD) point elsewhere in the same function. Entry 0 is not an opcode, so it points at _unknown_opcode, the error path, as do all the unused entries. The breakpoint also shows something about startup: the first frame CPython evaluates is not your program but <frozen importlib._bootstrap>, the import system, compiled into the binary as bytecode.

How much does it buy? I built the 3.6.5 source twice with the same gcc and the same flags, once --with-computed-gotos and once --without-computed-gotos, and ran four small loop-heavy workloads through both, alternating, three rounds each, taking the best of nine runs per round:

import sys, timeit

def total(xs):
    s = 0
    for x in xs:
        s += x
    return s

def sieve(n):
    flags = [True] * n
    count = 0
    for i in range(2, n):
        if flags[i]:
            count += 1
            for j in range(i * i, n, i):
                flags[j] = False
    return count

def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

def attrs(n):
    p = Point(1, 2)
    s = 0
    for i in range(n):
        s += p.x * p.y
    return s

xs = list(range(1000000))
work = [("total", lambda: total(xs)), ("sieve", lambda: sieve(1000000)),
        ("fib", lambda: fib(25)), ("attrs", lambda: attrs(1000000))]
for name, fn in work:
    print("%s %.4f" % (name, min(timeit.repeat(fn, number=1, repeat=9))))
WorkloadComputed gotos (s)Switch (s)Switch is slower by
total over a million ints0.01220.013510.7%
sieve(1000000)0.04580.04907.0%
fib(25)0.00760.009018.4%
attrs(1000000)0.03040.03112.3%

Each cell is the best of three rounds, and the rounds agreed closely: the computed-goto build won every one of the twelve pairings. The gain is largest where the work per instruction is smallest. fib is all calls, comparisons and small-integer arithmetic, where dispatch is a big share of the time. attrs spends most of its time in attribute lookup and integer multiplication, which no dispatch trick touches. On a processor with a weaker indirect-branch predictor the gap would likely be larger, since that is the hardware the trick works around.

What a name costs

The bytecode makes a promise that the language doesn’t: different kinds of names compile to different instructions, and those instructions do very different amounts of work.

  • LOAD_FAST: a local. An array index, as above.
  • LOAD_GLOBAL: a module-level name or a builtin. Two dictionary lookups, the second only if the first misses:
    /* namespace 1: globals */
    ix = globals->ma_keys->dk_lookup(globals, key, hash, &value_addr, NULL);
    if (ix == DKIX_ERROR)
        return NULL;
    if (ix != DKIX_EMPTY && *value_addr != NULL)
        return *value_addr;

    /* namespace 2: builtins */
    ix = builtins->ma_keys->dk_lookup(builtins, key, hash, &value_addr, NULL);

That’s _PyDict_LoadGlobal in Objects/dictobject.c. The name is a str whose hash was computed once and cached in the string object, so the cost is the probing, not the hashing.

  • LOAD_ATTR: obj.name. One call, PyObject_GetAttr(owner, name), which goes to the type’s tp_getattro slot. For an ordinary instance that is PyObject_GenericGetAttr. It first looks the name up in the type and its base classes (through a per-type cache), because a data descriptor such as a property must win over the instance. Then it looks in the instance’s __dict__. If the name was found only in the type and is a function, it builds a new bound method object pairing the function with the instance, which is allocated, returned, and freed when it’s no longer needed.

To measure only the lookups, each loop below has the same shape, a for over a list of a million Nones, and a body that is a single expression statement: the name is loaded and immediately thrown away (POP_TOP). Subtracting the empty loop leaves the cost of one load:

import timeit

N = 1000000
xs = [None] * N          # the loop's own cost, with nothing allocated per iteration
G = 1

class Box:
    def __init__(self):
        self.n = 1
    def m(self):
        pass

o = Box()

src = {
    "pass":                "def f(xs, o):\n    for x in xs:\n        pass",
    "x       (LOAD_FAST)": "def f(xs, o):\n    for x in xs:\n        x",
    "G       (LOAD_GLOBAL)": "def f(xs, o):\n    for x in xs:\n        G",
    "len     (LOAD_GLOBAL, builtin)": "def f(xs, o):\n    for x in xs:\n        len",
    "o.n     (LOAD_ATTR, instance)": "def f(xs, o):\n    for x in xs:\n        o.n",
    "o.m     (LOAD_ATTR, method)": "def f(xs, o):\n    for x in xs:\n        o.m",
}

results = {}
for label, text in src.items():
    ns = {"G": G}
    exec(text, ns)
    f = ns["f"]
    best = min(timeit.repeat(lambda: f(xs, o), number=1, repeat=15))
    results[label] = best / N * 1e9
base = results["pass"]
for label, t in results.items():
    extra = "" if label == "pass" else "  (+%.1f)" % (t - base)
    print("%-32s %5.1f ns per iteration%s" % (label, t, extra))
$ python3 lookups.py
pass                               2.8 ns per iteration
x       (LOAD_FAST)                3.4 ns per iteration  (+0.6)
G       (LOAD_GLOBAL)              5.9 ns per iteration  (+3.1)
len     (LOAD_GLOBAL, builtin)     6.9 ns per iteration  (+4.2)
o.n     (LOAD_ATTR, instance)     10.3 ns per iteration  (+7.5)
o.m     (LOAD_ATTR, method)       13.0 ns per iteration  (+10.3)

The empty loop, FOR_ITER, STORE_FAST and JUMP_ABSOLUTE three times a million, costs 2.8 nanoseconds per pass. A local adds 0.6. A global adds 3.1, five times as much, and a builtin like len adds 4.2, because the globals lookup has to miss before the builtins lookup can hit. An instance attribute adds 7.5: a lookup in the type that misses, then one in the instance dict that hits. A method adds 10.3, seventeen times a local. Its lookup in the type hits, its lookup in the instance dict misses, and then a bound-method object is made and destroyed every time.

What one name costs, and what a trace hook costs

Python 3.6.5, a loop of a million iterations, best of several runs on one machine.

Added to each pass, ns

xLOAD_FAST
+0.6
GLOAD_GLOBAL
+3.1
lenLOAD_GLOBAL (builtin)
+4.2
o.nLOAD_ATTR (instance)
+7.5
o.mLOAD_ATTR (method)
+10.3

The summing loop, ns per pass

no tracer
12.6
tracer, calls only
23.2
tracer, every line
113.2

Hover or focus a bar for details.

Left: each loop body is one expression statement, so a bar is one load and its POP_TOP, minus the empty loop (2.8 ns). Right: the loop from the top of the post, with no tracer, a tracer that only asks for calls, and one that asks for every line.

The leak: code shaped by the interpreter

These numbers explain idioms that make no sense in terms of the language and complete sense in terms of this loop. The best known is hoisting a method or a builtin into a local before a hot loop:

import timeit

N = 1000000
xs = list(range(N))

def appends(xs):
    out = []
    for x in xs:
        out.append(x)
    return out

def appends_alias(xs):
    out = []
    append = out.append
    for x in xs:
        append(x)
    return out

def lengths(xs):
    n = 0
    for x in xs:
        n += len(xs)
    return n

def lengths_alias(xs, len=len):
    n = 0
    for x in xs:
        n += len(xs)
    return n

for f in (appends, appends_alias, lengths, lengths_alias):
    best = min(timeit.repeat(lambda: f(xs), number=1, repeat=15))
    print("%-14s %5.1f ns per iteration" % (f.__name__, best / N * 1e9))
$ python3 aliases.py
appends         19.3 ns per iteration
appends_alias   13.1 ns per iteration
lengths         23.6 ns per iteration
lengths_alias   19.2 ns per iteration

append = out.append makes the bound method once, outside the loop, and keeps it in a local, which saves a third of the loop’s time. len=len as a default argument turns a two-dictionary lookup into an array index and saves a fifth. The standard library does both in places where speed matters, and both make the code worse to read. They exist because CPython compiles to bytecode once and then never learns anything at run time: it can’t notice that len has meant the same builtin for the last million iterations and stop looking it up. The len=len trick also changes behaviour. If someone rebinds len in the module after the function is defined, the function keeps the old one, because the default value was captured when def ran.

Python 3.7, now in its last beta, attacks the method case directly: it adds two opcodes, LOAD_METHOD and CALL_METHOD, which find the function and call it with the instance as the first argument without ever making the bound-method object. That removes the allocation part of the 10.3 nanoseconds above, though not the lookups. It’s a change to the interpreter, not the language, and it only helps the bytecode of obj.m() written as one expression. f = obj.m followed later by f() still makes the object.

Tracing: why the debugger is slow

Debuggers, coverage tools and profilers written in Python all use the same hook, sys.settrace(func), which asks the interpreter to call func on events: a call, a new line, a return, an exception. This is what that costs on the summing loop from the start of the post:

import sys, timeit

N = 1000000
xs = list(range(N))

def total(xs):
    s = 0
    for x in xs:
        s += x
    return s

def on_call(frame, event, arg):        # sees calls, asks for no line events
    return None

def on_every_line(frame, event, arg):  # what a coverage tool or debugger does
    return on_every_line

for label, tracer in (("no tracer", None), ("tracer, calls only", on_call),
                      ("tracer, every line", on_every_line)):
    sys.settrace(tracer)
    best = min(timeit.repeat(lambda: total(xs), number=1, repeat=7))
    sys.settrace(None)
    print("%-20s %7.1f ns per iteration" % (label, best / N * 1e9))
$ python3 tracing.py
no tracer               12.6 ns per iteration
tracer, calls only      23.2 ns per iteration
tracer, every line     113.2 ns per iteration

A tracer that asks only for call events, and so is never called inside the loop, still makes the loop almost twice as slow. The reason is in the dispatch macros quoted above: if (!_Py_TracingPossible && ...) guards the computed goto. _Py_TracingPossible counts the threads with a trace function, and while it’s non-zero, every instruction in every frame takes the long way round through fast_next_opcode, which calls maybe_call_line_trace to work out whether this instruction starts a new line. Asking for line events then adds a call into Python for each of the two lines in the loop body, and the loop is nine times slower than with no tracer.

This is why “run it under the debugger” and “run it with coverage” change timing so drastically, and why a race that shows up in production can vanish under a debugger. It’s also why profilers built on this hook, cProfile included, measure a program that runs differently from the one you care about: they add a fixed cost to every call and, in the line-tracing case, to every line.

The compiler does a little constant folding

The last stage before a code object is the peephole optimiser, Python/peephole.c. It does a few local rewrites, and the most visible one is constant folding: arithmetic on constants is done at compile time, and the result stored in co_consts. Its limits are C constants, and you can find them by asking for slightly too much:

def consts(src):
    return compile(src, "<folding>", "exec").co_consts

print(consts("x = 24 * 60 * 60"))
print(consts("x = 'ab' * 10"))
print(consts("x = 'ab' * 11"))
print(consts("x = 2 ** 64"))
print(consts("x = 2 ** 200"))
print(consts("x = (1, 2) + (3,)"))
print(consts("x = [1, 2] + [3]"))
print(consts("if x in [1, 2, 3]: pass"))
$ python3 folding.py
(24, 60, None, 1440, 86400)
('ab', 10, None, 'abababababababababab')
('ab', 11, None)
(2, 64, None, 18446744073709551616)
(2, 200, None)
(1, 2, 3, None, (1, 2), (3,), (1, 2, 3))
(1, 2, 3, None)
(1, 2, 3, None, (1, 2, 3))

24 * 60 * 60 is folded to 86400 (keeping the intermediate 1440, which nothing uses). 'ab' * 10 is folded, but 'ab' * 11, at 22 characters, is not. 2 ** 64 is folded and 2 ** 200 is not. The limits are at the top of the folding code:

#define MAX_INT_SIZE           128  /* bits */
#define MAX_COLLECTION_SIZE     20  /* items */
#define MAX_STR_SIZE            20  /* characters */
#define MAX_TOTAL_ITEMS       1024  /* including nested collections */

They exist so that x = 'a' * 10**9 in a function nobody calls doesn’t make a gigabyte .pyc. Tuples are folded because they are immutable; lists never are, because each evaluation must produce a new list. But x in [1, 2, 3] is rewritten to test against the constant tuple (1, 2, 3), because the compiler can see that the list is never exposed. In 3.7 this folding moves from the bytecode to the AST, where it can see more, but the limits come along with it.

Bytecode is a private format

The compiled form is cached on disk in __pycache__, so that the next import can skip compiling:

import importlib.util, marshal, os, py_compile, struct, time

print("MAGIC_NUMBER   ", importlib.util.MAGIC_NUMBER, "=",
      struct.unpack("<H", importlib.util.MAGIC_NUMBER[:2])[0])
os.utime("total.py", (1500000000, 1500000000))   # a fixed mtime, so the run is repeatable
path = py_compile.compile("total.py")
print("written to     ", path)
data = open(path, "rb").read()
print("header         ", data[:12].hex())
magic, mtime, size = struct.unpack("<4sII", data[:12])
print("  source mtime ", mtime, "=", time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(mtime)), "UTC")
print("  source size  ", size, "bytes; os.stat says", os.stat("total.py").st_size)
module = marshal.loads(data[12:])
print("then marshal   ", type(module).__name__, module.co_consts[0])
$ python3 pyc.py
MAGIC_NUMBER    b'3\r\r\n' = 3379
written to      __pycache__/total.cpython-36.pyc
header          330d0d0a002f685946000000
  source mtime  1500000000 = 2017-07-14 02:40:00 UTC
  source size   70 bytes; os.stat says 70
then marshal    code <code object total at 0x75c729db0030, file "total.py", line 1>

A .pyc in 3.6 is a 12-byte header and a marshal-serialised code object. The header is a magic number, the source file’s modification time and its size. On import, if the magic, the time and the size all match, the bytecode is loaded without recompiling. The magic number, 3379, is the bytecode format’s version, and the comment above it in Lib/importlib/_bootstrap_external.py is a history of every change since Python 3.0: “Python 3.6rc1 3379 (more thorough class validation #23722)”. It changes whenever an opcode is added, removed or changed, which happens in almost every release. A 3.6 .pyc means nothing to 3.7, which has the new method opcodes, and the file name says so: total.cpython-36.pyc.

This is a leak with practical consequences. Bytecode is not a portable format like Java’s class files. Tools that read it (dis, coverage, debuggers, bytecode-rewriting libraries) have to be updated for every release, and code that inspects co_code directly breaks on upgrade. The timestamp check is also why a .pyc can go stale when a source file is replaced by one with the same size and an old mtime, as a build system or a version-control checkout can do. 3.7 adds an option for exactly that case (PEP 552): .pyc files validated by a hash of the source instead of its timestamp, with a 16-byte header to make room.

What we covered

  • CPython compiles source in four C stages, tokens, parse tree and AST, symbol table and code object, and the code object holds the bytecode plus tables of constants, names and local variables.
  • Since 3.6, every instruction is two bytes, an opcode and an argument, with EXTENDED_ARG for bigger arguments. Local names become array indices at compile time.
  • One C function, _PyEval_EvalFrameDefault, runs all bytecode. Each instruction is an opcode body that works on a stack of PyObject * stored after the locals in the frame’s f_localsplus array. Frames live on the heap and link to their callers through f_back.
  • A debug build’s __ltrace__ prints every instruction and stack operation. Reading it showed a stack slot read out of bounds into the locals, and a trace flag that is a C static rather than a per-frame property.
  • With computed gotos, each opcode jumps straight to the next through a 256-entry table of label addresses inside the function. That beat a plain switch by 2 to 18% here.
  • A local costs an array index, a global two dict lookups, and a method a full attribute lookup plus a new bound-method object. Hoisting into locals is a workaround for an interpreter that never learns at run time, and 3.7’s LOAD_METHOD removes the bound-method part.
  • Any trace function disables the fast dispatch path for every instruction, and line tracing made a loop nine times slower.
  • The peephole optimiser folds constants within limits written in C, and the bytecode format is versioned by a magic number that changes in almost every release.

The next post goes down one level further: what happens to the C stack when Python calls Python, and why a deep enough recursion is not a Python error at all.

A note on the evidence

What I ran, and where. Everything ran on Ubuntu 18.04’s release userland, a minimal root built from the bionic release archive only: python3 3.6.5-3 ([GCC 7.3.0]), python3-dbg 3.6.5-3 for the trace, and gdb 8.1 with the release interpreter’s debug symbols from python3.6-dbg. For the dispatch comparison I built the v3.6.5 tag of CPython twice with 18.04’s gcc 7.3.0 and configure’s default flags, once with --with-computed-gotos and once with --without-computed-gotos, and nothing else changed. I ran everything as a chroot on one 64-bit x86 desktop machine, so the kernel was the host’s, not 18.04’s. Each script was extracted from this page and run as shown.

Timings. Every timing is the best of several runs (15 for the lookups and aliases, 7 for tracing, 9 per round for the dispatch comparison), run with nothing else using the machine. The absolute nanoseconds belong to that machine, a recent desktop processor, and an older or slower one would show larger numbers everywhere. The ratios are the point, and they held from run to run. The dispatch comparison alternated the two interpreters for three rounds. The table shows the best round for each, and the computed-goto build was faster in all twelve pairings. Running every script on this page again, extracted from the page itself, reproduced every listing exactly except the timings, which came back within 5% (the builtin lookup at +4.5 ns instead of +4.2), in the same order, and with the computed-goto build ahead on all four workloads. These builds don’t use Ubuntu’s profile-guided and link-time optimisation, so their absolute times differ from the stock python3’s. I compare them only with each other.

What I trimmed. The trace listing cuts the second and third passes of the loop, which repeat the first with 20 and 30, at the .... The figure shows every line. The gdb listing drops gdb’s start-up lines about threads and shared libraries.

What I worked out rather than read. The figure’s stack and locals are rebuilt from the trace’s pushes and pops, with two rules for what the debug build doesn’t print: GET_ITER replaces the top with the iterator, and INPLACE_ADD replaces the top with the value that the next STORE_FAST pops. That stackadj 30 printed the local x follows from f_localsplus putting the stack directly after the locals and from x being the last local; I didn’t confirm it with a debugger. The frame size arithmetic (384 bytes fixed) is derived from the measured 504 and the formula in frame_sizeof, not printed directly.

What I cited rather than ran. The C quoted here is from the CPython source at the v3.6.5 tag: Python/ceval.c, Python/opcode_targets.h, Include/frameobject.h, Objects/dictobject.c, Python/peephole.c and Lib/importlib/_bootstrap_external.py. The 3.7 changes (LOAD_METHOD and CALL_METHOD, folding moved to the AST, PEP 552’s hash-based .pycs) are as they stand in the v3.7.0b5 tag. Lua’s move to a register VM is from the Lua 5.0 implementation paper.

What I’d still change. The dispatch comparison is four workloads on one processor. A benchmark suite would give a fairer average, and an older processor would probably show a bigger gap. And timeit’s best-of-N hides variance. A careful study would report the spread, not just the minimum.

More