The boundary with C and zero-copy

The buffer protocol is an agreement on how to hand memory to someone else's code without copying. The whole scientific stack stands on it, and it also explains why numpy parallelizes with threads while an ordinary loop does not.

L1 · 9 minL2 · 11 min📱 phoneverified · CPython 3.11 + numpy 2.4, linux x86-64

1Predict

Commit to an output and a reason before you open the answer.

Snippet A
buf = bytearray(b"x" * 10_000_000)

# what does it cost to take half?
#   bytes(buf[:5_000_000])
#   memoryview(buf)[:5_000_000]
bytearray slice:  0.0185 s
memoryview slice: 0.000007 s
The very same half. 2800 times.
Snippet B
import array, numpy as np
arr = array.array("q", range(10))
n = np.frombuffer(arr, dtype=np.int64)
n[0] = 999
print(arr[0])
999
We wrote into a numpy array — and an object of the standard library changed.
Snippet C
import time, threading

def work(n=8_000_000):
    t = 0
    for i in range(n):
        t += i
    return t

t0 = time.perf_counter(); work(); work()
seq = time.perf_counter() - t0

ths = [threading.Thread(target=work) for _ in range(2)]
t0 = time.perf_counter()
for t in ths: t.start()
for t in ths: t.join()
par = time.perf_counter() - t0

print(f"sequentially: {seq:.2f} s")
print(f"two threads:  {par:.2f} s")
sequentially: 0.54 s
two threads:  0.50 s
Two cores, two threads, zero gain.
Snippet D
import time, threading
import numpy as np

M = np.random.rand(1600, 1600)
def work(): return M @ M

def wall(n_threads, repeat=5):
    best = float("inf")
    for _ in range(repeat):                     # best-of-5: a single measurement lies here
        ths = [threading.Thread(target=work) for _ in range(n_threads)]
        t0 = time.perf_counter()
        for t in ths: t.start()
        for t in ths: t.join()
        best = min(best, time.perf_counter() - t0)
    return best

work()                                          # warm-up
one, two = wall(1), wall(2)
print(f"one task:           {one:.3f} s")
print(f"two in two threads: {two:.3f} s")
print(f"speed-up:           {2*one/two:.2f}×")
one task:           0.119 s
two in two threads: 0.123 s
speed-up:           1.93×
The same interpreter, the same threads — a speed-up of 1.9 times.

2Mechanism

From lesson 03 we know that a list of objects and a contiguous buffer are different things. Here: how that buffer is passed between libraries, and what happens at the boundary with C.

The buffer protocol is an agreement: an object can hand out a pointer to its memory plus a description of the layout (element type, size, shape, strides).

memoryview is the Python way of using it: an object that looks into someone else's memory and copies nothing.

An extension can release the GIL for the duration of its work: the macros Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS around a section that does not touch Python objects.

Consequence 1 · a slice without a copy

Snippet A. A slice of a bytearray allocates five megabytes and copies them — work proportional to the size. A slice of a memoryview creates an object with a pointer and an offset: constant time regardless of size. Hence the 2800 times in the measurement, and the fact that the gap grows with the volume of data.

The practical conclusion is direct: parsing a binary format, reading headers, cutting packets — everything where data is read in pieces should go through memoryview. Otherwise every slice copies.

Consequence 2 · libraries talk to each other without copies

Snippet B. array.array implements the buffer protocol, numpy can read it — and np.frombuffer creates an array on top of the same memory. A write through one object is visible through the other, because the memory object is one.

This is what the whole scientific stack grew out of. numpy, torch, pandas, arrow, pillow, PIL buffers, CUDA arrays know nothing about each other, but can exchange data without copying — because they all implement one protocol. It is the one reason the stack can be assembled from independent libraries at all: without a shared agreement on memory, every hand-off of a hundred-megabyte array would cost a copy.

Consequence 3 · the GIL is released, and that changes everything

Snippets C and D are the most important pair in the lesson. One and the same interpreter, the same two threads, a different result.

Pure Python does not speed up: bytecode is executed under the GIL, and threads merely alternate (lesson 09, consequence 3). But numpy does speed up — because inside an array operation it releases the GIL and computes in C without touching Python objects. While one thread multiplies an array, the second can work too.

taskone tasktwo in two threads
a Python loop0.24 s0.48 s
a numpy operation0.121 s0.125 s

Hence a rule that otherwise looks like folklore: threads in Python are useful for everything that goes into C or into waiting — numpy, compression, hashing, database drivers, network calls. And useless for everything that stays in bytecode.

Consequence 4 · what was paid for it

All of this works because a C extension sees Python objects directly: their fields, their reference count, their slots. As cheap as it gets — and as rigid as it gets.

Since the reference count sticks out in the public API and thousands of extensions touch it without locks, the GIL cannot be removed without breaking all of them. The same protocol that gave the scientific stack its speed fixed the global lock in place for thirty years. Lesson 09 explained why the GIL appeared; here you can see why it does not go away.

3Limits of the model

Where this stops holding

Not every buffer is contiguous. memoryview can describe slices with a stride and multi-dimensional shapes, and such a buffer cannot simply be passed to a function expecting a flat array. Hence ValueError: ndarray is not C-contiguous and the explicit ascontiguousarray calls in other people's code.

An exported buffer blocks resizing. While a memoryview on a bytearray is alive, an attempt to change its length gives a BufferError — otherwise the pointer would dangle. This is the one place where Python behaves like C with its iterator invalidation.

Releasing the GIL is the extension author's decision 🔧. Not every numpy function releases it, and small operations do not release it at all — the overhead is greater than the gain. Check with a measurement, not on faith.

4Root

Root R6: extensions are written in C and see objects directly. The decision was made in 1991, when Python was conceived as a glue language for existing C libraries, and it turned out to be the most consistent in its history.

The buffer protocol in its current form appeared in 2006 (PEP 3118) as a generalization of older mechanisms: before it there were several incompatible ways of handing out memory, and numpy and PIL negotiated by hand. The new protocol described the layout formally — type, shape, strides — and thereby allowed arbitrary libraries to exchange arrays knowing nothing about each other.

It was this, not the speed of C, that made Python the language of numerical computing. Any compiled language gives speed; what is rare is a dozen independent libraries sharing one memory without copies.

5Analogy

memoryview is std::span, and the match is almost complete: a non-owning window into someone else's contiguous memory, created and sliced in constant time, with changes through the window visible to the owner. If you keep this in mind, the whole lesson comes down to one sentence: Python finally got a span, and the buffer protocol is the way to hand one out from any type.

The difference is in safety and its price. In C++ a span will happily outlive a vector that reallocated, and turn into a dangling pointer. In Python this is impossible: the view holds a reference to the owner, and the owner cannot change size while the view is alive — the attempt gives a BufferError. That is, Python pays for a span with a reference count and one prohibition, and in return removes a whole class of errors.

6Questions a careful reader asks

Questions that come up on their own if you read closely. The answer is under the question.

Why is numpy faster, if the processor inside is the same?

Because the point is not the speed of the arithmetic but how much work is done around it.

Adding two numbers in Python: read two pointers, check the types, call __add__, allocate a new object for the result, initialize its header, return a pointer. The arithmetic itself is one processor instruction out of about forty.

In numpy the data lies in a contiguous buffer of a fixed type, and the loop runs in C: types are checked once for the whole array, no objects are created at all, and the compiler applies vector instructions — one operation on four or eight numbers at once.

Three sources of gain, and it is useful to tell them apart:

  • No objects. A million numbers is 8 MB instead of 36, and zero allocations instead of a million.
  • No interpretation. A loop in C instead of six nanoseconds per bytecode instruction.
  • Data in a row. The CPU cache works as intended, not as it does when jumping around the heap.

Hence an important point: numpy speeds up not “maths” but vector operations on homogeneous data. Element access a[i] in a Python loop is slower than on a list, because on every access a number object has to be created anew. If a Python loop over the array remains in the code, there will be no gain.

memoryview — when is it really needed?

When data is cut into pieces rather than read whole: a slice of bytes copies, a slice of memoryview does not.

import timeit
setup = "data = bytearray(10_000_000); mv = memoryview(data)"
print(timeit.timeit("data[1000:9_000_000]", setup, number=100))
print(timeit.timeit("mv[1000:9_000_000]", setup, number=100))
# a difference of thousands of times

The measurement in this lesson: 0.0185 s versus 0.000007 s. Copying eight megabytes versus arithmetic on a pointer.

Where this solves the problem. Parsing a binary protocol in which frames are cut out of a buffer in a loop: the naive version copies the whole tail on every frame, that is, O(n²) in volume. Reading a large file in blocks with header parsing. Passing a slice of an array to a C function without a copy.

Two things people usually learn the hard way. The first: a memoryview retains the original buffer — while a hundred-byte slice is alive, the whole ten-megabyte bytearray lives. If a small piece is needed for a long time, you must explicitly make bytes(frame) out of it.

The second: while even one memoryview exists, the original bytearray cannot be resized — BufferError: Existing exports of data: object cannot be re-sized. This is protection, not caprice: the buffer could have moved in memory.

And the main thing — it is a shared protocol, not a feature of one type. It is through it that numpy, torch, arrow and pillow exchange arrays without copies.

Why do not all numpy operations release the GIL?

Because releasing and re-acquiring the GIL takes time in itself, and on small work that costs more than it gains.

Releasing means two operations on the global lock plus a possible switch of OS threads. For an operation lasting a microsecond the overhead is greater than the operation itself; for one lasting a hundred milliseconds it is unnoticeable.

So numpy releases the GIL selectively: in heavy ufunc loops, in matrix operations through BLAS, in sorting large arrays. Small operations, work with object arrays (dtype=object) and everything that touches Python objects do not release it 🔧 — and cannot: objects must not be accessed without the GIL.

Check with a measurement, not on faith. The measurement from this lesson:

task                      one    two in threads    gain
Python loop              0.24 s      0.48 s          none
numpy operation         0.121 s     0.125 s          1.9×

A useful sign: if an operation is expressed as one call on a large array, it probably releases the GIL. If it is a Python loop around small calls, it certainly does not.

And be careful with BLAS: it is often multi-threaded itself, and then the measurement will show a speed-up that will not be there with OMP_NUM_THREADS=1. When comparing options, pin this variable, otherwise you are measuring something other than you think.

Rewriting a piece in C or Rust — when does it pay off?

Later than you would like. It is the fifth lever of five, and the first four almost always give more.

The order from lesson 21: algorithm → data structure → leaving the object model → leaving the interpreter → rewriting. Replacing a list with a set in a membership check gives 154 times; rewriting in C usually gives from three to fifty, and only on the piece that was rewritten.

The full price people forget to count:

  • Build infrastructure: a compiler in CI, wheels for every platform, manylinux — the whole of lesson 16.
  • Errors become segfaults instead of exceptions, and the whole process goes down.
  • Managing references by hand: a missing Py_DECREF is a leak, an extra one is memory corruption.
  • A second language in the project: review, hiring, maintenance.

When it is really justified: a hot loop that the profiler shows as the only bottleneck; work that cannot be expressed as vector operations (parsers, graph traversals, specific algorithms); the need to release the GIL and parallelize across cores.

What to try first: numpy or polars for tabular data, Cython with typed variables (local edits, simpler build), numba for numerical loops (JIT, no separate build). Rust through PyO3 is a good choice once the decision has been made: there is no manual reference management there, and that removes half the risks in the list above.

Bottom line. The buffer protocol is an agreement on handing out memory without copying: a pointer plus a description of the layout. Hence memoryview, whose slice costs constant time versus copying for a bytearray — 2800 times on five megabytes in the measurement. Hence also the fact that numpy, torch, arrow and pillow exchange arrays knowing nothing about each other: they implement one protocol, and that is the one reason the scientific stack can be assembled from independent libraries. And hence the main practical point: an extension can release the GIL while it works in C, so two threads with numpy give 1.9×, while two threads with a pure loop give precisely nothing. The price of the agreement is the reference count in the public C API, because of which the GIL cannot be removed without breaking thousands of extensions: the same mechanism that gave the stack its speed fixed the global lock in place.
From here on — optional
counterfactualC, C++ span and RustA pointer plus a length — and what an agreement on layout adds to that

C passes an array as a pointer plus a length, and that is exactly what the buffer protocol does — only C has no agreement on what the elements are. Hence the whole class of type-mismatch errors that the buffer protocol removes: it carries the element format as a string and checks it on export.

std::span from C++20 is almost literally memoryview: a non-owning view of contiguous memory, constructed for free, sliced for free. And the problem is the same: a span outlives its owner — and you get a dangling pointer. Python is protected from this by two mechanisms: a memoryview holds a reference to the owner (lesson 09), and resizing while a view is alive is forbidden.

Rust solves the same thing with slices and borrowing, but checks it with the compiler: a slice cannot outlive its owner, because that does not compile. The price is an ownership model you have to keep in your head; the gain is the same safety without a reference count.

Three ways of handing out memory: with no guarantees, with a lifetime guarantee at runtime, with a guarantee at compile time.

🐛 bugA copy where a view was expectedParsing a binary protocol with bytes slices — quadratic work out of nowhere

A parser reads frames from a buffer. The logic is right; the amount of copying is not.

def parse_frames(data: bytes):
    frames = []
    while data:
        length = int.from_bytes(data[:4], "big")
        frames.append(data[4:4+length])
        data = data[4+length:]          # ← a copy of the remainder on every iteration
    return frames

The last line copies the whole unread tail on every frame. For a buffer of N bytes and K frames that is on the order of N·K bytes copied — on ten megabytes and a thousand frames it comes to several gigabytes of copying, while the data is only ten megabytes.

Review lets it through because the code reads perfectly and runs instantly on small inputs. It shows up at real size, and the profiler shows the time inside the slice — that is, in the line that looks free.

def parse_frames(data: bytes):
    mv = memoryview(data)
    frames, pos = [], 0
    while pos < len(mv):
        length = int.from_bytes(mv[pos:pos+4], "big")
        frames.append(mv[pos+4:pos+4+length])
        pos += 4 + length
    return frames

Not a single copy: all the slices are windows into the original buffer. The measurement from snippet A gives the scale of the gain — constant versus linear time per slice.

A caveat that also follows from the mechanism: the returned frames keep the whole original buffer alive (lesson 09). If out of ten megabytes you need a hundred bytes that will outlive the rest, make a copy there, deliberately, through bytes(frame).

⚡ 1.9×Threads for whatever goes into CThe GIL is released inside numpy — and ThreadPoolExecutor suddenly works

“Threads in Python are useless for computation” is exactly half true, and the other half is worth money.

taskone tasktwo in two threadsgain
a Python loop0.24 s0.48 snone
a numpy operation0.121 s0.125 s1.9×
from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor(max_workers=4) as ex:
    results = list(ex.map(heavy_numpy_op, chunks))

This works only because numpy releases the GIL inside the operation. The same holds for zlib and gzip, hashlib, pillow, reading and writing files, database drivers, lxml — everywhere the heavy part runs in C.

Why threads and not processes. Processes will give parallelism too, but the data will have to be serialized and sent over: a hundred-megabyte array through multiprocessing is pickle there and back. Threads share memory for free, and on arrays that often tips the balance.

How to check your case in a minute: measure sequentially and in two threads. It sped up — the extension releases the GIL, and you can scale. It did not — either everything is in bytecode, or the particular function does not release the GIL; then processes, or rewriting the hot piece.

The rule: before choosing processes, measure threads. They are cheaper, and on numerical code often sufficient.

💻 terminalCheck it in the REPLFour snippets plus BufferError, C-contiguity and shared memory

Run the snippets and check them against your prediction. Then:

buf = bytearray(b"abcdef")
mv = memoryview(buf)
buf.extend(b"xyz")
# What will happen, and why exactly that?

import numpy as np
a = np.arange(12).reshape(3, 4)
print((a.flags["C_CONTIGUOUS"], a.T.flags["C_CONTIGUOUS"]))
# Why does transposing break contiguity, if the data is the same?

import numpy as np
a = np.arange(10)
b = a[::2]
b[0] = 99
print(a[0])
# A copy or a view? And how do you check for certain?

import array, sys
arr = array.array("q", range(1000))
mv = memoryview(arr)
print((sys.getsizeof(mv), mv.nbytes))
# Why do the two numbers differ so much?

The first question is the most important one: the BufferError here is not a usage error but a mechanism protecting against a dangling pointer.

sourcememoryview in the standard libraryWhere zero-copy is applied deliberately, and what it gave

Lib/socket.py, the recv_into method, and readinto on file objects. The whole *_into line in the standard library exists for the sake of consequence 1: read not “into a new object” but into a buffer already allocated. For a server handling thousands of connections, that is the difference between an allocation per packet and reusing one buffer.

Lib/multiprocessing/shared_memory.py. Here the buffer protocol solves a task that cannot be solved otherwise: memory shared between processes, on top of which numpy makes an array without copying. Read it and notice that the whole library is a thin wrapper over a system call plus a buffer export; the heavy part is already in the protocol.

Modules/_io/bufferedio.c. Buffered I/O in C: you can see both the work with raw memory and the places where Py_BEGIN_ALLOW_THREADS stands around a system call. It is exactly these macros that make file I/O in threads parallel — consequence 3 in the source.

L2What a buffer looks like, and what it means to release the GILPy_buffer, strides and contiguity; the macros around a critical section

From L1 you know about the agreement. Here: what it consists of.

The Py_buffer structure carries: a pointer to the data, a reference to the owner object, the total size in bytes, the element size, a format string ("q" for int64, "d" for double), the number of dimensions, a shape array and a strides array. Strides are how many bytes to the next element along each dimension; they are exactly what makes it possible to describe a transposed matrix without moving the data.

import array
arr = array.array("q", range(10))
m = memoryview(arr)
print((m.format, m.itemsize, m.nbytes, m.shape, m.strides))
# → ('q', 8, 80, (10,), (8,))

Contiguity is a derived property: a buffer is C-contiguous if the strides are exactly what they would be with dense packing. Transposing changes the strides and contiguity is lost, although the data did not move — hence the question from the “Check it yourself” section.

Releasing the GIL looks like this in an extension's code:

Py_BEGIN_ALLOW_THREADS
/* no PyObject may be touched here:
   neither reading fields nor changing a reference count */
result = compute_over_raw_memory(ptr, n);
Py_END_ALLOW_THREADS

The macros save the thread state, release the lock and take it back. There is exactly one condition, and it is strict: inside, Python objects must not be touched. That is why numpy releases the GIL on a vector operation over a raw buffer and does not release it where it has to call a Python callback — for example, in np.vectorize over an ordinary function.

A practical rule of thumb: if an operation works on a whole dtype array, the GIL is probably released; if there is an object array or a Python call inside, it is not.

L3Where this is in the CPython sourcesmemoryobject.c, ceval_gil.h, PEP 3118

Tag v3.11.15.

  • Objects/memoryobject.c — the whole implementation of memoryview, including the contiguity checks and the export counting that gives rise to BufferError.
  • Include/cpython/object.h — the Py_buffer structure and the bf_getbuffer and bf_releasebuffer slots. Twenty lines that define the whole protocol.
  • Python/ceval_gil.h — what exactly Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS do.
  • PEP 3118 — the protocol itself; the motivation lists the incompatible mechanisms it replaced.
connectionsWhere this leadsL03, L09, L19 · the contrast with span in C++ and Rust slices
root R6 · The C API as the way to extend
← foundation L03 · Containers — why a contiguous buffer and a list of objects are different things
← foundation L09 · Reference counting — why the GIL appeared, and why a view holds on to its owner
↔ contrast std::span in C++: the same window, but it can outlive its owner
↔ contrast Rust slices: the same safety, checked by the compiler instead of a count
→ next L16 · Packages and rewriting — ABI, wheels, and when to move code into C or Rust
→ next L19 · The GIL — why what helps here turns out to be a limitation there
readingFurther readingPEP 3118 🟧 · memoryview 🟦 · memoryobject.c 🟥

Written by · The Python Canon