Contents
cython-example is a small repository from 2021. It holds one short function written twice, once in Python and once in Cython, a setup.py that compiles the Cython one, and a script that times both. It is a learning example, not a library, and it has no tests apart from that timing script.
It is still a good size for seeing what Cython does to your code. The three parts are the .pyx file, the build and the comparison.
What the .pyx file changes
example_original.py adds up the integers below x:
def test(x):
y = 0
for i in range(x):
y += i
return yexample_cython.pyx is the same loop with declarations added:
cpdef test(int x):
cdef int y = 0
cdef int i
for i in range(x):
y += i
return yA .pyx file is Cython source: Python syntax plus a few extra keywords. In this repo it has to be compiled before Python can import it. The loop body is identical, so the whole change is in the declarations.
| Python version | Cython version | What it does |
|---|---|---|
def test(x) | cpdef test(int x) | x becomes a C int, and the function gets both a C entry point and a Python-callable wrapper |
y = 0 | cdef int y = 0 | y becomes a C int that only compiled code can see |
i created by the loop | cdef int i | the loop counter becomes a C int |
y += i | y += i | same text, but both operands are now C integers |
The repo's own comments say cpdef is usable from both Cython and Python, and cdef variables only from Cython. A plain cdef function would be callable only from other Cython code, so cpdef (or def) is what lets the ordinary Python in testing_things.py reach it.
Why the typed version should be faster
In the Python version every value is a Python object. Each y += i asks the interpreter to add two objects and build a result object. In the Cython version y and i are declared as C integers, so the C code that Cython generates can add them with the C + operator. With a typed counter and a typed x, for i in range(x) can also become a plain C for loop instead of going through Python's iterator machinery.
That is the expected mechanism, not a measurement. The repo commits no output, and I have not added one here.
How setup.py builds it
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize('example_cython.pyx'))The README gives the two commands, and requirements.txt pins Cython==0.29.23:
pip install -r requirements.txt
python setup.py build_ext --inplacecythonize translates the .pyx file into C source and returns an extension definition. build_ext then compiles that C file with your system's C compiler, so you need one installed. --inplace puts the compiled module next to the source, which is why import example_cython works afterwards from the same folder.
The .gitignore lists build, __pycache__ and env, but not the generated C file or the compiled module, so a careless git add . would pick them up. Also, distutils was removed from the standard library in Python 3.12. On a new interpreter I would change the first line to from setuptools import setup.
How the test script compares them
The core of testing_things.py, trimmed:
import timeit
cy = timeit.timeit('''example_cython.test(5000)''', setup='import example_cython', number=1000)
py = timeit.timeit('''example_original.test(5000)''', setup='import example_original', number=1000)
print('Cython is {}x faster'.format(py/cy))timeit.timeit runs the setup string once, then runs the statement 1000 times and returns the total in seconds. Both versions get the same input and the same repetition count, so py/cy is a fair ratio for this one loop. The script also imports multiprocessing, but only to print the CPU count. Nothing runs in parallel.
Two things are missing. It never checks that both functions return the same value, and it prints "Cython is ... faster" even if the ratio comes out below 1.
Where the two versions stop agreeing
For x = 5000 the answer is 12,497,500, which fits in a 32-bit signed integer. The sum passes 2,147,483,647 when x reaches 65537. Past that point the Cython version no longer computes what the Python version does, because a C int has a fixed width and a Python int grows as needed. Signed overflow is undefined behaviour in C, so I would not rely on any particular result. An x that does not fit in a C int raises OverflowError at the call.
When this is worth doing
This repo is a demonstration, and a function this small is not worth compiling. The idea scales to numeric loops that a profiler shows are hot and that existing compiled libraries cannot replace. For everything else, the compiler requirement and the platform-specific binary cost more than they save. If I extended this script I would add an equality check first and a larger input second.
Found this useful? Share it with your team.