Writing the C Side by Hand

Contents
The same C function, long add(long a, long b) { return a + b; }, called from Python 3.7 costs 9.7
nanoseconds through a hand-written extension using the new METH_FASTCALL convention, 26.5 through
the classic argument-tuple convention, 46 through pybind11, 51 through cffi and 189 through ctypes.
The addition itself takes about a nanosecond. Everything else is the boundary between Python and C:
packing and unpacking arguments, converting Python ints to C longs and back, and the reference
counting that has to be exactly right at every crossing, because a single missing Py_INCREF frees
an object that something else is still using, and the program goes on running with garbage.
This post writes an extension module by hand, about as small as one can be, and uses it to show the C API’s contract from the C side: how arguments arrive, how errors are reported, who owns each reference, and what happens to a program when the C code gets one of them wrong. Then it measures the boundary itself, through every common way of crossing it.
This is Part 10 of a series on the CPython runtime. Part 4 followed reference counts from the Python side, and Part 5 used the debug allocator to catch a one-byte overflow. It is written for Python programmers who have written a little C. Everything here ran on CPython 3.7.4, built from its tag with Ubuntu 18.04’s gcc 7.3.0, with cffi 1.12.3, Cython 0.29.13 and pybind11 2.3.0 from PyPI, the latest of each at the time. The note at the end says exactly where and how.
An extension module
An extension module is a shared library that exports one function, PyInit_<name>, which returns a
module object. Everything Python can call in it is described by a table of PyMethodDef entries: a
name, a C function pointer, a flag saying which calling convention the function uses, and a docstring.
Here is the whole of spam.c, six functions, four of them correct:
#define PY_SSIZE_T_CLEAN
#include <Python.h>
/* add(a, b): the classic convention: a tuple of arguments, parsed by a format string */
static PyObject *
spam_add(PyObject *self, PyObject *args)
{
long a, b;
if (!PyArg_ParseTuple(args, "ll", &a, &b))
return NULL; /* PyArg_ParseTuple has set the exception */
return PyLong_FromLong(a + b); /* a new reference, owned by the caller */
}
/* add_fast(a, b): METH_FASTCALL, new in 3.7: the arguments arrive as a C array */
static PyObject *
spam_add_fast(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
{
if (nargs != 2) {
PyErr_SetString(PyExc_TypeError, "add_fast() takes exactly 2 arguments");
return NULL;
}
long a = PyLong_AsLong(args[0]);
if (a == -1 && PyErr_Occurred())
return NULL;
long b = PyLong_AsLong(args[1]);
if (b == -1 && PyErr_Occurred())
return NULL;
return PyLong_FromLong(a + b);
}
/* first_buggy(lst): returns lst[0] -- with a bug */
static PyObject *
spam_first_buggy(PyObject *self, PyObject *lst)
{
return PyList_GetItem(lst, 0); /* a BORROWED reference, returned as if new */
}
/* first(lst): the same, correctly */
static PyObject *
spam_first(PyObject *self, PyObject *lst)
{
PyObject *item = PyList_GetItem(lst, 0);
if (item == NULL)
return NULL;
Py_INCREF(item); /* now it is ours to give away */
return item;
}
/* leaky(n): makes n ints and never releases them */
static PyObject *
spam_leaky(PyObject *self, PyObject *arg)
{
long n = PyLong_AsLong(arg);
for (long i = 0; i < n; i++) {
PyObject *x = PyLong_FromLong(1000000 + i); /* a new reference... */
(void)x; /* ...never Py_DECREF'd */
}
Py_RETURN_NONE;
}
/* forgot(): reports failure without saying what failed */
static PyObject *
spam_forgot(PyObject *self, PyObject *unused)
{
return NULL; /* no PyErr_SetString first */
}
static PyMethodDef spam_methods[] = {
{"add", spam_add, METH_VARARGS, "Add two C longs."},
{"add_fast", (PyCFunction)(void (*)(void))spam_add_fast, METH_FASTCALL, "Add, without a tuple."},
{"first_buggy", spam_first_buggy, METH_O, "lst[0], with a reference bug."},
{"first", spam_first, METH_O, "lst[0]."},
{"leaky", spam_leaky, METH_O, "Leak n ints."},
{"forgot", spam_forgot, METH_NOARGS, "Fail without an exception."},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef spammodule = {
PyModuleDef_HEAD_INIT, "spam", "A hand-written extension module.", -1, spam_methods
};
PyMODINIT_FUNC
PyInit_spam(void)
{
return PyModule_Create(&spammodule);
}
and a three-line setup.py to compile it against the running interpreter’s headers:
from distutils.core import setup, Extension
setup(name="spam", ext_modules=[Extension("spam", ["spam.c"])])
$ python3 setup.py -q build_ext --inplace
The result is spam.cpython-37m-x86_64-linux-gnu.so. The suffix says which interpreter it is for:
CPython 3.7, built with pymalloc (m), on 64-bit Linux. Extensions are compiled against one minor
version’s object layouts, so this file won’t load in 3.6 or 3.8. Part 2 found the same about bytecode,
and the C API has the same boundary.
The contract, from the C side
import spam
print("spam.add(2, 3) =", spam.add(2, 3))
print("spam.add_fast(2, 3) =", spam.add_fast(2, 3))
for call in ("spam.add('2', 3)", "spam.add(2**64, 3)", "spam.forgot()"):
try:
eval(call)
except Exception as e:
print("%-20s -> %s: %s" % (call, type(e).__name__, e))
$ python3 use.py
spam.add(2, 3) = 5
spam.add_fast(2, 3) = 5
spam.add('2', 3) -> TypeError: an integer is required (got type str)
spam.add(2**64, 3) -> OverflowError: Python int too large to convert to C long
spam.forgot() -> SystemError: <built-in function forgot> returned NULL without setting an error
Three rules of the C API are visible here.
Arguments arrive as objects. With METH_VARARGS, the interpreter packs the arguments into a new
tuple and passes it, and PyArg_ParseTuple unpacks it according to a format string, "ll" for two C
longs, converting each and checking types. With METH_FASTCALL, added to the documented API in 3.7,
the function gets a pointer to the arguments where they already are, on the caller’s value stack, and
their count. No tuple is made, and the function converts each argument itself. Either way the C code
sees PyObject *s and must turn them into C values, which can fail.
Failure is NULL plus an exception. Every C API function that returns an object returns NULL
on failure, after setting the thread’s current exception with a function like PyErr_SetString.
PyArg_ParseTuple set TypeError for the string and OverflowError for 264, which
doesn’t fit a C long, and the extension only had to pass the NULL on. A function that returns
NULL without setting anything breaks the contract, and the interpreter’s call machinery
(_Py_CheckFunctionResult in Objects/call.c) detects it and raises SystemError instead, naming the
function. Part 1’s hash(-1) == -2 is the same convention for functions that return a C number: −1
means “check for an exception”, which is why PyLong_AsLong returning −1 must be followed by
PyErr_Occurred().
Every reference has an owner. PyLong_FromLong returns a new reference: the caller owns one
count and must eventually release it, which spam_add does by returning it, passing ownership on to
its own caller. PyList_GetItem returns a borrowed reference: the list still owns it, and the caller
may use it only while the list keeps it alive. The C compiler knows none of this. The documentation of
every API function says which kind it returns.
A borrowed reference, returned as if owned
first_buggy returns PyList_GetItem’s borrowed reference directly. The interpreter assumes any
returned object is a new reference and, when the caller is done with it, decrements its count. That
decrement was never paid for:
import spam, sys
lst = [[1, 2, 3]] # the inner list's only reference is lst's slot
print("references to lst[0]:", sys.getrefcount(lst[0]) - 1)
x = spam.first(lst)
print("after x = first(lst): ", sys.getrefcount(lst[0]) - 1)
del x
x = spam.first_buggy(lst)
print("after x = first_buggy(lst):", sys.getrefcount(lst[0]) - 1, " (should be 2)")
del x # drops a reference nobody took: the list is freed
print("after del x: lst[0] is now freed memory that lst still points to")
print("lst[0] =", lst[0])
$ python3 -u borrowed.py
references to lst[0]: 1
after x = first(lst): 2
after x = first_buggy(lst): 1 (should be 2)
after del x: lst[0] is now freed memory that lst still points to
lst[0] = [[...]]
$ echo $?
0
The correct first raised the count to 2, and del x brought it back to 1. first_buggy left it at 1
while x also refers to the list, so del x took it to zero and freed the inner list while lst still
held a pointer to it. Nothing complained. The next line printed lst[0] = [[...]], a list containing
itself, which lst[0] never was.
That output depends on how the memory was reused. The list’s struct went onto the list free list from
Part 5, at the same address, still claiming a length of 3. Its array of item pointers was freed back to
pymalloc and reused for something else, and repr read whatever pointers live there now. A probe of the
same situation found id(lst[0]) unchanged and len(lst[0]) still 3. In a larger program the reuse is
different every time: a dangling object can show stale values, print another object’s contents, or
crash long after the bug, in code that has nothing to do with it.
Under the debug allocator, with its freed blocks overwritten with a marker byte, the same program crashed:
$ PYTHONMALLOC=debug python3 -u borrowed.py
references to lst[0]: 1
after x = first(lst): 2
after x = first_buggy(lst): 1 (should be 2)
after del x: lst[0] is now freed memory that lst still points to
lst[0] = [[...]]
Segmentation fault
$ echo $?
139
It printed the same wrong line before crashing, which says the corruption itself wasn’t caught. The
debug allocator fills freed blocks so that later use is more likely to fail loudly, and the program
died with a segmentation fault, exit status 139, at some later use of the dead memory. That’s the
usual way reference-counting bugs surface: as a crash somewhere else, later. The fix is one line, the
Py_INCREF in first.
Who owns lst[0]?
The inner list's reference count after each statement of borrowed.py, and who holds the references.
Counts are what the script printed, except the final 0, which follows from the 1 before it: a freed object has no count to print. The holders follow from the code.
A missing decref: a leak nothing reports
The opposite mistake keeps a count too high. leaky creates n integers and drops its pointer to each
without releasing it, so each keeps a count of 1 forever:
import spam, tracemalloc
tracemalloc.start()
for round in range(3):
spam.leaky(100000)
print("after %d calls of leaky(100000): %5.1f MB still allocated" %
(round + 1, tracemalloc.get_traced_memory()[0] / 1e6))
$ python3 leak.py
after 1 calls of leaky(100000): 2.8 MB still allocated
after 2 calls of leaky(100000): 5.6 MB still allocated
after 3 calls of leaky(100000): 8.4 MB still allocated
Each call leaks 100,000 ints of 28 bytes, 2.8 MB, and the total only grows. No exception is raised,
nothing is printed, and the cycle collector can’t help, because ints aren’t containers and these have
a nonzero count with no referrer it could find. tracemalloc sees it because it records every
allocation made through Python’s allocators, including those from C extensions, and
tracemalloc.take_snapshot() can attribute them to the Python line that called into C. A debug
build’s sys.gettotalrefcount(), the running sum of every object’s reference count, would rise by
100,000 per call. Most extension leaks are found one of those two ways.
What the boundary costs
The same add crossed the boundary eight ways. The Python function and operator.add are there for
comparison. The others are the extension’s two conventions, a Cython def function with typed
arguments (def add(long a, long b): return a + b), a pybind11 binding of a C++ long add(long, long),
the same C function through cffi’s API mode (compiled into a module) and through ctypes (a plain shared
library loaded at run time):
import ctypes, operator, timeit
import spam, add_cy, add_pb
from _add_cffi import lib as cffi_lib
libadd = ctypes.CDLL("./libadd.so")
libadd.add.argtypes = (ctypes.c_long, ctypes.c_long)
libadd.add.restype = ctypes.c_long
def py_add(a, b):
return a + b
candidates = [
("Python def", py_add),
("C ext, METH_VARARGS", spam.add),
("C ext, METH_FASTCALL", spam.add_fast),
("operator.add (C)", operator.add),
("Cython 0.29 def", add_cy.add),
("cffi 1.12, API mode", cffi_lib.add),
("pybind11 2.3", add_pb.add),
("ctypes", libadd.add),
]
N = 1000000
base = min(timeit.repeat("pass", number=N, repeat=7)) / N * 1e9
for label, f in candidates:
assert f(2, 3) == 5
t = min(timeit.repeat("f(2, 3)", globals={"f": f}, number=N, repeat=7)) / N * 1e9
print("%-22s %6.1f ns per call" % (label, t - base))
$ python3 callcost.py
Python def 24.2 ns per call
C ext, METH_VARARGS 26.5 ns per call
C ext, METH_FASTCALL 9.7 ns per call
operator.add (C) 11.9 ns per call
Cython 0.29 def 20.2 ns per call
cffi 1.12, API mode 50.9 ns per call
pybind11 2.3 45.8 ns per call
ctypes 189.2 ns per call
(How the five modules were built is in the note at the end.)
One call of add(2, 3), eight ways
CPython 3.7.4, nanoseconds per call above an empty statement. The addition itself is about one nanosecond.
Hover or focus a bar for details.
The grey bar is the same addition as a Python function, for scale. Everything else calls the one-line C function long add(long a, long b).
METH_FASTCALL: 9.7 ns. The cheapest way across: no tuple, twoPyLong_AsLongs, onePyLong_FromLong.operator.add, a C function in the standard library that callsPyNumber_Add, is in the same range.METH_VARARGS: 26.5 ns, nearly three times as much, for the same C function. The difference is building a tuple for the arguments and interpreting a format string to unpack it. It’s slower than the Python function (24.2 ns), whose arguments the interpreter copies straight into a new frame.- Cython: 20.2 ns. Cython generated the argument handling, including the conversion from Python
ints to C
longs, and its code is faster than the hand-written tuple version. - pybind11 and cffi: about 46 and 51 ns. Both do more general work per call: pybind11 tries each overload’s type casters in turn, and cffi checks and converts every argument against the declared C signature.
- ctypes: 189 ns, the most expensive by far. It builds a C call frame at run time through
libffi, converting each argument through itsargtypesobjects, for a function it knows only by name.
Calling C to add two numbers is never faster than adding them in Python, because the boundary costs more than the work. C pays off only when each call does much more work than the call costs: a loop over an array, a parse of a buffer, a hash of a file. The cost ranking above also tracks how much each tool knows at compile time. The hand-written FASTCALL function knows everything. ctypes knows nothing until the call is made.
What we covered
- An extension module is a shared library with a
PyInit_function and aPyMethodDeftable, compiled against one CPython minor version’s ABI. - Arguments arrive as a tuple (
METH_VARARGS, parsed by format string) or, since 3.7, as a C array (METH_FASTCALL). Errors areNULLplus a set exception, andNULLalone becomes aSystemError. - Every reference is new, borrowed or stolen. Returning a borrowed reference as new freed a list still
in use, and the program printed garbage, then crashed under the debug allocator. A missing
Py_DECREFleaked 2.8 MB per call, visible only totracemalloc. - Calling the same C
addcost 9.7 ns throughMETH_FASTCALL, 26.5 throughMETH_VARARGS, 20 through Cython, about 46 through pybind11, 51 through cffi and 189 through ctypes.
The next post covers the other way C and Python share data: without copying it, through the buffer protocol, the interface between Python objects and raw C memory that NumPy is built on.
A note on the evidence
What I ran, and where. Everything ran on CPython 3.7.4, built from the v3.7.4 tag with Ubuntu
18.04’s gcc 7.3.0, on a minimal 18.04 userland from the release archive, as a chroot on a 64-bit x86
machine. cffi 1.12.3, Cython 0.29.13 and pybind11 2.3.0 were installed from PyPI with that interpreter’s
pip, the newest releases of each before this post. spam.c and setup.py are as shown. The other
modules were built as follows: libadd.so from long add(long a, long b) { return a + b; } with
gcc -O2 -shared -fPIC; the cffi module by ffibuilder.set_source("_add_cffi", ...) and
ffibuilder.compile() with the same function; the Cython module from the one-line add_cy.pyx above
with cythonize -i; the pybind11 module from PYBIND11_MODULE(add_pb, m) { m.def("add", &add); }
with g++ 7.3.0, -O2 -std=c++11. Each script was extracted from this page and run as shown.
The numbers. The call costs are the best of seven timeit repeats of a million calls each, minus
the cost of an empty statement, with nothing else running. The listing on this page is from a run made
specifically to capture these outputs. An earlier run gave every figure within 3% (9.6, 25.8, 20.6,
45.3, 50.1 and 186.6 ns), in the same order. The reference counts and the leak are deterministic. What
the dangling lst[0] prints is not, and it printed the same in both runs here only because the two
runs did the same work.
What I worked out rather than read. The explanation of [[...]] (the list struct on the free list,
its item array reused) is supported by a probe that found the address and length unchanged. I didn’t
identify what reused the item array. Why each binding tool costs what it does is from their general
designs, not from profiling them.
What I cited rather than ran. The calling-convention and ownership rules are from the 3.7
documentation (Doc/c-api/structures.rst, which marks METH_FASTCALL “versionadded 3.7”, and the
reference-count notes on each function), and _Py_CheckFunctionResult from Objects/call.c at
v3.7.4.
What I’d still change. A benchmark of one tiny function measures only the crossing. A comparison
of the same tools on a function that does real work, a loop over a buffer, would show where each stops
mattering. And METH_FASTCALL isn’t part of the limited API, so an extension that uses it gives up the
stable ABI that would let one binary load in several Python versions.
Writing the C Side by Hand