Writing C in Cython
cythonpythonperformancec-extensionsmemory-management
Abstraction: Using Cython to write C-speed code with Python syntax
Key points:
- Cython allows writing raw C structs and arrays directly with minimal syntactic sugar, achieving C/C++ speed without learning the Python C API
- Both the Cython and C implementations of an N-body physics simulation are ~70x faster than equivalent pure Python/NumPy code
- cymem library wraps malloc/free: remembers allocated addresses and frees them all when the Pool is garbage-collected, preventing memory leaks
- Typed memory-views (intermediate Cython approach) allow NumPy multi-dimensional array features but feel more complex; raw structs preferred for sparse data
- Pattern inverts traditional "write Python, optimize hot spots in C" workflow — instead write Cython throughout from the start
- Took ~30 minutes to write Cython version vs full C implementation, with identical performance
Connections: Cython · Numpy · High Performance Computing · Python Performance
Source: http://honnibal.wordpress.com/2014/10/21/writing-c-in-cython/