← Writing

The Other Engines

26 min readSystemsPythonCpythonCPypyJit
Contents

The same five-line function takes 0.34 seconds on CPython 3.8, 7 milliseconds on PyPy, 6 on Numba and 5 as typed Cython. Run it on PyPy with the JIT switched off and it takes 0.56 seconds, slower than CPython. Then hand a list of a million integers to a small C extension, once, and PyPy’s own built-in sum() over that list goes from 1.9 milliseconds to 52 and stays there, because the C extension asked for something PyPy only has to fake: a C array of PyObject* pointers, which is what a Python list is in CPython and not in PyPy.

This post runs one benchmark on four engines that run Python code without being CPython’s eval loop, and then looks at what each of them has to give up. The answer is the theme of this whole series from the other side: so much of what Python programs depend on is CPython’s C, its reference counts, its object layout and its C API, that every other engine has to choose between being fast and being compatible.

This is Part 14 of a series on the CPython runtime. Part 2 took apart the eval loop that every engine here replaces, Part 9 the integers they all have to get right, and Part 10 the C API that PyPy has to imitate. It is written for Python programmers who have written a little C. Everything here ran on a stock Ubuntu 20.04, released three days ago, using only its release archive: CPython 3.8.2, PyPy 7.3.1, Cython 0.29.14, Numba 0.48 and gcc 9.3. The note at the end says exactly where and how.

The benchmark

import sys, time

def f(n):
    total = 0
    for i in range(n):
        total += i * i % 7
    return total

N = 10_000_000
for r in range(5):
    t = time.perf_counter()
    s = f(N)
    print("round %d: %.3f s  (%d)" % (r, time.perf_counter() - t, s))

It is the worst case for CPython and the best case for everything else: a tight loop of integer arithmetic, where Part 2’s eval loop spends nearly all its time dispatching opcodes and Part 9’s integers spend the rest allocating, checking and freeing PyLongObjects for values that would fit in a register. On CPython:

$ python3 bench.py
round 0: 0.341 s  (19999999)
round 1: 0.341 s  (19999999)
round 2: 0.339 s  (19999999)
round 3: 0.340 s  (19999999)
round 4: 0.340 s  (19999999)

That’s 34 ns per iteration, for eleven bytecodes and three new integer objects.

PyPy: a Python interpreter written in Python

PyPy is an implementation of Python written in RPython, a restricted subset of Python 2 that can be compiled ahead of time. The PyPy interpreter is an ordinary bytecode interpreter, with a loop very like CPython’s ceval.c, written in RPython and translated to C as a whole program. On its own, that interpreter is slower than CPython’s:

$ pypy3 --jit off bench.py
round 0: 0.562 s  (19999999)
round 1: 0.560 s  (19999999)
round 2: 0.561 s  (19999999)
round 3: 0.557 s  (19999999)
round 4: 0.562 s  (19999999)

With its JIT on:

$ pypy3 bench.py
round 0: 0.008 s  (19999999)
round 1: 0.007 s  (19999999)
round 2: 0.007 s  (19999999)
round 3: 0.007 s  (19999999)
round 4: 0.007 s  (19999999)

48 times faster than CPython, 0.7 ns an iteration, including the first round, which paid for compiling. What changed is that PyPy stopped interpreting.

Reading the trace

PyPy will write out what it compiled. PYPYLOG names the log categories and a file:

def f(n):
    total = 0
    for i in range(n):
        total += i * i % 7
    return total

print(f(100000))
$ PYPYLOG=jit-log-opt,jit-summary:trace.log pypy3 trace.py
199999

The log has every loop compiled and every operation in it, with each guard’s list of the values it must save. A short script prints the last loop compiled, which is f’s, from its loop header to its jump back:

# jitloop.py: print the last loop in a PYPYLOG jit-log-opt file, from its last label to its jump
import sys
ops = open(sys.argv[1]).read().split("\n")
start = max(i for i, op in enumerate(ops) if "label(" in op)
end = next(i for i in range(start, len(ops)) if "jump(" in ops[i])
for op in ops[start + 1:end + 1]:
    if op.startswith("debug_merge_point"):
        print("    # " + op.split("~#")[1].rstrip("')"))      # the bytecode this came from
    elif op.strip():
        print(op.split(" [")[0])                                # drop each guard's list of saved values
$ python3 jitloop.py trace.log
    # 14 FOR_ITER
+576: i52 = int_lt(i51, i25)
+579: guard_true(i52, descr=<Guard0x737539cf8200>)
+585: i54 = int_add(i51, 1)
    # 16 STORE_FAST
    # 18 LOAD_FAST
    # 20 LOAD_FAST
    # 22 LOAD_FAST
    # 24 BINARY_MULTIPLY
+589: setfield_gc(p15, i54, descr=<FieldS pypy.module.__builtin__.functional.W_IntRangeIterator.inst_current 8>)
+593: i55 = int_mul_ovf(i51, i51)
+600: guard_no_overflow(descr=<Guard0x737539cf8260>)
    # 26 LOAD_CONST
    # 28 BINARY_MODULO
+606: i58 = int_eq(i55, -9223372036854775808)
+606: i60 = int_rshift(i55, 63)
+613: i61 = int_xor(i55, i60)
+619: i63 = uint_mul_high(i61, -7905747460161236406)
+632: i65 = uint_rshift(i63, 2)
+636: i66 = int_xor(i65, i60)
+639: i68 = int_mul(i66, 7)
+643: i69 = int_sub(i55, i68)
    # 30 INPLACE_ADD
+646: i70 = int_add_ovf(i46, i69)
+652: guard_no_overflow(descr=<Guard0x737539cfa338>)
    # 32 STORE_FAST
    # 34 JUMP_ABSOLUTE
+658: guard_not_invalidated(descr=<Guard0x737539cfa380>)
+658: i72 = getfield_raw_i(126947404257152, descr=<FieldS pypysig_long_struct.c_value 0>)
+671: i74 = int_lt(i72, 0)
+675: guard_false(i74, descr=<Guard0x737539cfa3c8>)
    # 14 FOR_ITER
+681: jump(p0, p1, p6, p9, i70, i51, p15, i54, i25, descr=TargetToken(126947318292592))

This is the whole loop, and it’s worth reading slowly, because every line is something CPython does on every iteration and PyPy has reduced to an instruction or two.

The # 14 FOR_ITER to # 34 JUMP_ABSOLUTE comments are the bytecodes of f, the same ones dis showed in Part 2, at the same offsets. Most of them compiled to nothing: STORE_FAST, the three LOAD_FASTs and LOAD_CONST have no operations under them, because the trace keeps local variables in registers (i51 is i, i46 is total), not in a frame’s array of PyObject*. The i in names like i55 means a machine integer. There are no objects in this loop at all: the integers are unboxed, and no PyLongObject (or PyPy’s W_IntObject) is allocated anywhere.

FOR_ITER became a compare and a guard: i52 = int_lt(i51, i25), is the counter below the end of the range, and guard_true(i52), leave if not. The setfield_gc writes the range iterator’s position back to memory, because the iterator is a real object that outlives the loop.

BINARY_MULTIPLY became int_mul_ovf followed by guard_no_overflow. This is Part 9’s leak in reverse. A Python integer can’t overflow, so CPython checks the size of every result, and so must PyPy, but here the check is one guard on the CPU’s overflow flag: if i * i ever doesn’t fit in 64 bits, the guard fails and execution falls back to the interpreter, where integers are arbitrary precision. The same happens for the += (int_add_ovf).

BINARY_MODULO became eight operations with no division in them. Dividing by a constant 7 is done by multiplying by a precomputed reciprocal (-7905747460161236406 is it, as a 64-bit pattern) and taking the high half (uint_mul_high), the same trick a C compiler uses. The rshift and xor operations around it handle a negative dividend, so that the result follows Python’s rule for %, which rounds the quotient down, rather than C’s, which truncates it. The JIT could treat the divisor as a constant because a guard_value in the first, peeled copy of the loop, outside this part, pinned the function’s constants.

JUMP_ABSOLUTE became two checks. guard_not_invalidated fails if something the trace assumed has been changed elsewhere, such as a global being rebound or a class being modified. The getfield_raw_i reads a word that PyPy’s signal handling sets, and guard_false leaves the loop if it is set. That is PyPy’s version of the eval breaker from Part 6: the place where a pending signal or a thread switch gets its chance.

And then jump back to the label. Twenty-one operations, five of them guards, for what CPython does in eleven trips through Part 2’s switch.

The cost of getting there

None of this happens at the start. PyPy starts every program in its interpreter, counting, and has a few thresholds that it will print:

$ pypy3 --jit help | awk -v RS= '/^ (threshold|function_threshold|trace_eagerness)=/'
 function_threshold=N
    number of times a function must run for it to become traced from start
    (default 1619)
 threshold=N
    number of times a loop has to run for it to become hot (default 1039)
 trace_eagerness=N
    number of times a guard has to fail before we start compiling a bridge
    (default 200)

A loop becomes hot after 1,039 iterations, and is then traced and compiled while the program waits. To see the effect, call f with a small n many times and time each call:

import json, sys, time

def f(n):
    total = 0
    for i in range(n):
        total += i * i % 7
    return total

times = []
for call in range(1, 201):
    t = time.perf_counter()
    f(2000)
    times.append((time.perf_counter() - t) * 1e6)
for call in (1, 2, 3, 4, 5, 10, 20, 50, 100, 199, 200):
    print("call %3d: %8.1f us" % (call, times[call - 1]))
json.dump(times, open("warm_%s.json" % sys.implementation.name, "w"))
$ python3 warmup.py
call   1:     58.4 us
call   2:     53.4 us
call   3:     48.0 us
call   4:     49.6 us
call   5:     48.4 us
call  10:     55.1 us
call  20:     47.7 us
call  50:     46.7 us
call 100:     47.6 us
call 199:     46.5 us
call 200:     48.0 us
$ pypy3 warmup.py
call   1:    469.5 us
call   2:      6.7 us
call   3:      3.3 us
call   4:      2.9 us
call   5:      2.8 us
call  10:      2.7 us
call  20:      2.7 us
call  50:      2.6 us
call 100:      2.6 us
call 199:      2.7 us
call 200:    103.8 us

CPython is the same on every call. PyPy’s first call is about eight times slower than CPython’s, because 1,039 iterations into it the loop became hot, and the rest of the call waited while it was traced, optimised and compiled to machine code. From the third call on, it’s fifteen to eighteen times faster than CPython.

And then call 200 is slow again, in every run I made. The reason is the guard on FOR_ITER. Every call ends by leaving the loop through that guard, because the range runs out, and a guard that fails is handled by a slow path back to the interpreter. After 200 failures (trace_eagerness), PyPy decides this exit is common enough to compile as well, and traces a bridge: a piece of machine code that starts where the guard failed and continues from there, so the next exit doesn’t need the interpreter. The log’s summary counts it:

$ PYPYLOG=jit-summary:js.log pypy3 warmup.py > /dev/null; grep "Total #" js.log
Total # of loops:	5
Total # of bridges:	1

(Five loops, against two in a version of the script without the json dump, so three belong to the standard library. One bridge, the loop exit.)

The same call, two hundred times

Time per call of f(2000), microseconds, log scale.

CPython 3.8.2PyPy 7.3.1

Hover, or focus and use the arrow keys.

CPython takes about 48 µs on nearly every call. PyPy's first call includes tracing and compiling the loop; the 200th includes compiling a bridge for the loop's exit, after its 200th failure of the same guard.

This is why PyPy benchmarks are always quoted “after warm-up”, and why a short-running program, a command-line tool or a test suite that runs every function once, can be slower on PyPy than on CPython. Startup on its own is close:

# wall.py: run each command three times and report the best wall time
import subprocess, sys, time
for cmd in sys.argv[1:]:
    best = float("inf")
    for _ in range(3):
        t = time.perf_counter()
        subprocess.run(cmd, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        best = min(best, time.perf_counter() - t)
    print("%6.2f s  %s" % (best, cmd))
$ python3 wall.py "python3 -c pass" "pypy3 -c pass" "python3 -c 'import numba'"
  0.01 s  python3 -c pass
  0.02 s  pypy3 -c pass
  0.16 s  python3 -c 'import numba'

Where PyPy stops pretending

PyPy runs the same Python code, and aims to behave the same, and nearly always does. Where it doesn’t, it’s because a program depended on something that is CPython’s implementation rather than the language. Each of the earlier parts of this series found one of those, and PyPy is a good way to see which they were.

Reference counting, Part 4. PyPy has no reference counts. Its garbage collector, incminimark, is generational and incremental, and moves young objects: memory is reclaimed when the collector runs, not when the last reference goes. Anything a program left to deterministic destruction happens later:

import gc

def write():
    f = open("out.txt", "w")
    f.write("written\n")        # no close(): f just goes out of scope

write()
print("after write():  ", repr(open("out.txt").read()))
gc.collect()
print("after collect():", repr(open("out.txt").read()))
$ python3 finalise.py
after write():   'written\n'
after collect(): 'written\n'
$ pypy3 finalise.py
after write():   ''
after collect(): 'written\n'

On CPython the file object is freed the moment write() returns, and its destructor flushes and closes it. On PyPy it’s still waiting to be collected, the data is still in its buffer, and the file on disk is empty until gc.collect() runs the finaliser. A program that opens files in a loop and never closes them works on CPython and runs out of file descriptors on PyPy, which is why PyPy’s documentation of its differences from CPython starts with this one.

Objects as addresses, Part 1. PyPy’s objects can move, so id() can’t be an address. And PyPy goes further than CPython’s small-integer cache: it makes is on integers, floats and a few other types compare values, and keeps x is y equivalent to id(x) == id(y) by computing id from the value. Part 1’s tools for looking at objects don’t exist:

import sys
a = 10 ** 20
b = a + 0
print("a is b:", a is b)
print("id(a) == id(b):", id(a) == id(b))
print("has getrefcount:", hasattr(sys, "getrefcount"))
try:
    print("getsizeof(1):", sys.getsizeof(1))
except TypeError as e:
    print("getsizeof(1): TypeError:", [l for l in str(e).splitlines() if "always" in l][0].split(", and")[0])
$ python3 ids.py
a is b: False
id(a) == id(b): False
has getrefcount: True
getsizeof(1): 28
$ pypy3 ids.py
a is b: True
id(a) == id(b): True
has getrefcount: False
getsizeof(1): TypeError: sys.getsizeof(object, default) will always return default on PyPy

Two different PyLongObjects on CPython, and on PyPy one value with one identity. sys.getrefcount doesn’t exist because there’s nothing to count, and sys.getsizeof raises with an explanation several paragraphs long, of which the gist is that the size of one object isn’t a meaningful question in PyPy. Instances share layouts (PyPy’s maps, which play the part of Part 8’s key-sharing dictionaries), and a list of small integers is stored as an array of machine integers, with no integer objects in it at all until someone reads one.

That last fact is the one that matters next.

cpyext: pretending to be CPython in C

A C extension doesn’t use Python. It uses CPython: the PyObject* struct from Part 1, with its reference count and type pointer, macros like Py_INCREF and PyList_GET_ITEM that read straight from those structs, and functions like PyArg_ParseTuple from Part 10. That’s the C API, and since there is no other specification of what a C extension may do, the C API is the spec. Compiling against it compiles against CPython’s memory layout.

PyPy supports C extensions anyway, through an emulation layer called cpyext. Here’s a small extension from Part 10’s pattern, with one function that adds two numbers and one that sums a list by reading its items directly:

#include <Python.h>

static PyObject *add(PyObject *self, PyObject *args)
{
    long a, b;
    if (!PyArg_ParseTuple(args, "ll", &a, &b))
        return NULL;
    return PyLong_FromLong(a + b);
}

static PyObject *total(PyObject *self, PyObject *list)
{
    long sum = 0;
    Py_ssize_t n = PyList_Size(list);
    for (Py_ssize_t i = 0; i < n; i++)
        sum += PyLong_AsLong(PyList_GET_ITEM(list, i));   /* a borrowed PyObject* */
    return PyLong_FromLong(sum);
}

static PyMethodDef methods[] = {
    {"add", add, METH_VARARGS, NULL},
    {"total", total, METH_O, NULL},
    {NULL, NULL, 0, NULL}
};

static struct PyModuleDef module = {PyModuleDef_HEAD_INIT, "spam", NULL, -1, methods};

PyMODINIT_FUNC PyInit_spam(void) { return PyModule_Create(&module); }

The same source compiles for both, against each interpreter’s own Python.h. PyPy ships one, with the same names and different insides:

# build_spam.py: compile spam.c against the running interpreter's headers
import subprocess, sys, sysconfig
out = "spam" + sysconfig.get_config_var("EXT_SUFFIX")
cmd = ["gcc", "-O2", "-shared", "-fPIC", "-I" + sysconfig.get_paths()["include"], "spam.c", "-o", out]
subprocess.run(cmd, check=True)
print(" ".join(cmd))
$ python3 build_spam.py
gcc -O2 -shared -fPIC -I/usr/include/python3.8 spam.c -o spam.cpython-38-x86_64-linux-gnu.so
$ pypy3 build_spam.py
gcc -O2 -shared -fPIC -I/usr/lib/pypy3/include spam.c -o spam.pypy36-pp73-x86_64-linux-gnu.so

Then the same measurements on each:

import sys, time, spam

def add(a, b):
    return a + b

def per_call(fn, n=2_000_000):
    best = float("inf")
    for _ in range(5):
        t = time.perf_counter()
        for _ in range(n):
            fn(2, 3)
        best = min(best, time.perf_counter() - t)
    return best / n * 1e9

def ms(fn, arg):
    t = time.perf_counter()
    fn(arg)
    return (time.perf_counter() - t) * 1e3

data = list(range(1_000_000))
print(sys.implementation.name)
print("  Python add(2, 3):    %6.1f ns" % per_call(add))
print("  C spam.add(2, 3):    %6.1f ns" % per_call(spam.add))
print("  sum(data):           %6.2f ms" % ms(sum, data))
print("  spam.total(data):    %6.2f ms" % ms(spam.total, data))
print("  spam.total again:    %6.2f ms" % ms(spam.total, data))
print("  sum(data) after:     %6.2f ms" % ms(sum, data))
$ python3 calls.py
cpython
  Python add(2, 3):      23.7 ns
  C spam.add(2, 3):      23.9 ns
  sum(data):             3.65 ms
  spam.total(data):      2.93 ms
  spam.total again:      2.68 ms
  sum(data) after:       3.43 ms
$ pypy3 calls.py
pypy
  Python add(2, 3):       0.4 ns
  C spam.add(2, 3):      95.2 ns
  sum(data):             1.88 ms
  spam.total(data):     94.92 ms
  spam.total again:     16.26 ms
  sum(data) after:      52.26 ms

On CPython, nothing surprising: a Python function and a C function cost about the same to call, and the C loop over the list is a little faster than sum().

On PyPy, every line is a different story.

  • Python add(2, 3) at 0.4 ns isn’t a call at all. Almost certainly the JIT inlined add into the timing loop, where with constant arguments there’s nothing left to do, so this measures an empty loop. (I didn’t read that trace.) The number is real and meaningless, which is a fair summary of microbenchmarks on a JIT.
  • C spam.add(2, 3) costs 95 ns, four times CPython’s. The JIT can’t see into C, so every call leaves compiled code, makes PyObject structs for the arguments that C can read, calls through cpyext’s versions of PyArg_ParseTuple and PyLong_FromLong, and turns the result back into a PyPy object.
  • spam.total(data) costs 95 ms the first time, against 3 on CPython. PyList_GET_ITEM is a macro that returns a pointer into the list’s array of PyObject*, and PyPy’s list has no such array: it holds a million machine integers. In PyPy 7.3.1’s cpyext/listobject.py, PyList_GET_ITEM calls convert_to_cpy_strategy on the list, which switches the list’s storage to a C array of PyObject* pointers, and making those means making a million C-visible integer objects, each linked to a PyPy object the collector knows about.
  • spam.total again is 16 ms, with the array already there, which is the cost of a million PyLong_AsLong calls through the emulation.
  • sum(data) after is the leak. The list is still in its converted form. It is now a list of PyObject* pointers, and PyPy’s own sum(), which took 1.9 ms on a list of machine integers, takes 52 ms on it, for the rest of the program’s life. One call into C changed the representation of a Python object, and Python code that never touches C again pays for it.

One call into C changes a PyPy list for good

Milliseconds for each operation on one list of a million ints, in the order calls.py runs them.

sum(data)
PyPy's list holds machine integers
CPython3.65 ms
PyPy1.88 ms
spam.total(data), first call
PyList_GET_ITEM converts the list to PyObject* storage
CPython2.93 ms
PyPy94.92 ms
spam.total(data), again
already converted; each item still crosses cpyext
CPython2.68 ms
PyPy16.26 ms
sum(data), after
the list stays converted
CPython3.43 ms
PyPy52.26 ms

A call to a C function costs 23.9 ns on CPython and 95.2 ns on PyPy. On CPython nothing here changes the list; on PyPy, PyPy's own sum() over it is 28 times slower afterwards.

This is why PyPy recommends cffi, which it ships built in, and which doesn’t expose PyPy’s objects to C at all: C code receives C values, not PyObject*s, so there’s nothing to emulate. And it’s why so much of the scientific Python stack, which is C extensions all the way down, runs on PyPy but rarely runs faster there.

Cython: Python compiled to C API calls

Cython takes the opposite route. It’s a compiler from Python, plus optional C type declarations, to a C extension module for CPython. Without declarations it compiles the function unchanged:

def f(n):
    total = 0
    for i in range(n):
        total += i * i % 7
    return total

With declarations, i and total become C longs:

def f(long n):
    cdef long total = 0, i
    for i in range(n):
        total += i * i % 7
    return total

def squares(long n):
    cdef long total = 0, i
    for i in range(n):
        total += i * i
    return total

Each goes from .pyx to C to a shared library:

# build_cy.py: Cython to C, then C to an extension module, for the running interpreter
import subprocess, sysconfig
for m in ("f_plain", "f_typed"):
    subprocess.run(["cython3", "-3", m + ".pyx"], check=True)
    out = m + sysconfig.get_config_var("EXT_SUFFIX")
    subprocess.run(["gcc", "-O2", "-shared", "-fPIC", "-I" + sysconfig.get_paths()["include"], m + ".c", "-o", out], check=True)
    print("%s.pyx -> %s.c (%d lines) -> %s" % (m, m, sum(1 for _ in open(m + ".c")), out))
$ python3 build_cy.py
f_plain.pyx -> f_plain.c (3087 lines) -> f_plain.cpython-38-x86_64-linux-gnu.so
f_typed.pyx -> f_typed.c (2784 lines) -> f_typed.cpython-38-x86_64-linux-gnu.so

Five lines of Python became three thousand lines of C, most of it module set-up. To see what one line became, a short script finds the comment Cython puts above the C for each source line:

# showc.py: print the C that Cython generated for one line of a .pyx file
import sys
src, tag = sys.argv[1], '/* "%s' % sys.argv[2]
c = open(src).read().split("\n")
start = next(i for i, l in enumerate(c) if l.strip().startswith(tag))
end = next(i for i in range(start + 1, len(c)) if c[i].strip().startswith('/* "'))
body = [l for l in c[start + 1:end] if l.strip() and not l.startswith(" *")]   # drop the quoted source
print("\n".join(body))
$ python3 showc.py f_plain.c 'f_plain.pyx":4'
    __pyx_t_1 = PyNumber_Multiply(__pyx_v_i, __pyx_v_i); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 4, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_1);
    __pyx_t_5 = __Pyx_PyInt_RemainderObjC(__pyx_t_1, __pyx_int_7, 7, 0, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 4, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_5);
    __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
    __pyx_t_1 = PyNumber_InPlaceAdd(__pyx_v_total, __pyx_t_5); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 4, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_1);
    __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
    __Pyx_DECREF_SET(__pyx_v_total, __pyx_t_1);
    __pyx_t_1 = 0;

That’s total += i * i % 7 without types: the same C API calls the eval loop would make for BINARY_MULTIPLY, BINARY_MODULO and INPLACE_ADD, PyNumber_Multiply and the rest, on the same PyObject*s, with the same reference counting, and the error check after each that Part 10 wrote by hand. What’s gone is the eval loop itself: no bytecode, no dispatch, no value stack. With types:

$ python3 showc.py f_typed.c 'f_typed.pyx":4'
    __pyx_v_total = (__pyx_v_total + __Pyx_mod_long((__pyx_v_i * __pyx_v_i), 7));
  }
$ grep -A4 "^static CYTHON_INLINE long __Pyx_mod_long(long a, long b)" f_typed.c
static CYTHON_INLINE long __Pyx_mod_long(long a, long b) {
    long r = a % b;
    r += ((r != 0) & ((r ^ b) < 0)) * b;
    return r;
}

One line of C arithmetic, which gcc compiles to a few instructions. Cython kept one piece of Python’s semantics, the sign of %, in __Pyx_mod_long, which corrects C’s remainder when the signs differ. It didn’t keep the other:

import time, f_plain, f_typed

def squares(n):
    total = 0
    for i in range(n):
        total += i * i
    return total

for name, fn in (("Cython, untyped", f_plain.f), ("Cython, typed", f_typed.f)):
    t = time.perf_counter()
    s = fn(10_000_000)
    print("%-16s %.3f s  (%d)" % (name, time.perf_counter() - t, s))
print("Python squares:", squares(10_000_000))
print("Cython squares:", f_typed.squares(10_000_000))
$ python3 cy.py
Cython, untyped  0.166 s  (19999999)
Cython, typed    0.005 s  (19999999)
Python squares: 333333283333335000000
Cython squares: 1291890006563070912

Untyped, Cython halves CPython’s time by removing the interpreter. Typed, it’s 68 times faster, and also wrong when the numbers get large. The sum of ten million squares is about 3.3 × 10²⁰, which doesn’t fit in a 64-bit long, and the typed version wrapped around without a word, which is what signed overflow does in practice in C, and is formally undefined. cdef long means C’s integers, with C’s overflow, and Python’s integers don’t overflow. This is Part 9’s NumPy leak again: the speed comes from giving up the check that made the abstraction safe.

Numba: compiling the subset it can type

Numba compiles Python functions to machine code at run time, through LLVM. It reads the function’s bytecode, infers a type for every variable from the types of the arguments on the first call, and generates code for that combination:

import time, numba

@numba.njit
def f(n):
    total = 0
    for i in range(n):
        total += i * i % 7
    return total

t = time.perf_counter(); f(10); print("first call (compiles): %.3f s" % (time.perf_counter() - t))
for r in range(3):
    t = time.perf_counter()
    s = f(10_000_000)
    print("round %d: %.4f s  (%d)" % (r, time.perf_counter() - t, s))
$ python3 nb.py
first call (compiles): 0.036 s
round 0: 0.0060 s  (19999999)
round 1: 0.0061 s  (19999999)
round 2: 0.0060 s  (19999999)

36 ms to compile on the first call, and then 6 ms, the same as PyPy and typed Cython. Its integers are 64-bit machine integers too, with the same overflow as Cython’s. @numba.njit means nopython mode: the compiled function may not use Python objects at all, only the types Numba knows how to lower to machine values, which are numbers, NumPy arrays, tuples, and a growing list of others. Anything else is a compile error at the first call:

import json, numba

@numba.njit
def report(rows):
    return json.dumps(rows)

try:
    report([[1, 2], [3, 4]])
except numba.errors.TypingError as e:
    print("\n".join(str(e).splitlines()[:2]))
$ python3 nbfail.py
Failed in nopython mode pipeline (step: nopython frontend)
Unknown attribute 'dumps' of type Module(<module 'json' from '/usr/lib/python3.8/json/__init__.py'>)

Numba doesn’t run your Python program faster. It runs a typed numerical language faster, and that language happens to be spelled in Python’s syntax, which is a fine thing to be, and a different thing.

One loop, six ways

f(10,000,000), seconds, log scale. Bars span 1 ms to the time taken; shorter is faster.

CPython 3.8.2 (baseline)
0.339 s · 1×
PyPy 7.3.1, JIT off
0.557 s · 1.6× slower
Cython, untyped
0.166 s · 2× faster
PyPy 7.3.1
7 ms · 48× faster
Numba 0.48
6 ms · 56× faster
Cython, typed
5 ms · 68× faster
1 ms10 ms100 ms1 s

Numba's time excludes its first call, which compiled the function in 36 ms. PyPy's is its best round; its first, which included compiling, took 8 ms. Typed Cython and Numba use 64-bit integers that overflow silently; CPython and PyPy keep Python's integers.

Python 2’s last release, and the engines it took with it

What we covered

  • PyPy’s interpreter alone is slower than CPython (0.56 against 0.34 s). Its tracing JIT made the same loop 48 times faster than CPython, by tracing the interpreter running the loop and optimising the interpreter out of the trace.
  • The compiled loop holds integers in registers, checks Python’s no-overflow promise with one guard_no_overflow per operation, and replaces % 7 with a multiply.
  • Compiling costs: the first call was eight times slower than CPython’s, and the 200th was slow again while a bridge for the loop’s exit was compiled.
  • PyPy differs where programs depended on CPython’s implementation: no reference counts (files not flushed until collected), ids that aren’t addresses and is that compares integer values, no getrefcount and no getsizeof.
  • cpyext emulates the C API. A C call costs four times CPython’s, and PyList_GET_ITEM converts a list into an array of PyObject*s, after which PyPy’s own sum() over it was 28 times slower.
  • Cython without types removes the eval loop but keeps every C API call, for a 2× gain. With types it’s 68× faster, and integers overflow silently.
  • Numba compiles a typed subset of Python through LLVM, 36 ms on the first call, as fast as typed Cython after, and refuses anything outside the subset.

The next post looks at the step every Python program takes before any of this, importing, which turns out to be a lot of system calls, a lot of executed code, and the place where Part 11’s shadowed module came from.

A note on the evidence

What I ran, and where. Everything ran in a chroot of Ubuntu 20.04 (focal), built with debootstrap from the release archive, with the release archive’s packages only: python3 3.8.2-0ubuntu2, pypy3 7.3.1+dfsg-4 (PyPy 7.3.1, Python 3.6.9, built 22 April), cython3 0.29.14-0.1ubuntu3, python3-numba 0.48.0-1build1 with python3-llvmlite 0.31.0-1, and gcc 9.3.0. The chroot ran on a newer host kernel, which doesn’t affect anything measured here. Each script was extracted from this page and run as shown, with outputs captured to files and pasted from them.

The numbers. Benchmark times are single runs of the rounds shown: five for CPython and PyPy, three for Numba, one each for the two Cython builds. calls.py takes the best of five for per-call costs and one run for each list operation. I ran it twice more before the run shown, and the PyPy list numbers were within 15% each time (the first spam.total took 91 to 106 ms, and sum after it 52 to 57 ms). The warm-up spike at call 200 appeared in every one of eight runs. The one-off spikes elsewhere in some runs, 20 to 70 µs, didn’t repeat and I didn’t investigate them. A complete rerun of every command on this page, extracted from the page, reproduced every output except the timings, which moved by up to 4% (the PyPy C-call and list numbers by up to 16%), with the bridge again on call 200 and PyPy’s sum() again 29 times slower after the C call.

What I read rather than ran. What PyList_GET_ITEM does is from pypy/module/cpyext/listobject.py at the release-pypy3.6-v7.3.1 tag. The identity and finalisation behaviour, and the reasons for getsizeof, are from that tag’s pypy/doc/cpython_differences.rst (and from the TypeError’s own text). The JIT parameters are from pypy3 --jit help. That the getfield_raw_i in the trace is PyPy’s signal flag is from its descriptor name, pypysig_long_struct. Release dates are from the projects' tags: CPython v2.7.18 (20 April), Jython v2.7.2 (21 March), Numba 0.48.0 (27 January).

Not covered. Numba 0.49 (16 April) is newer than 20.04’s package, and I used the package. PyPy also ships a Python 2.7 interpreter, which I didn’t run. And I didn’t try PyPy’s vec option, which is off by default, on this loop.

More