This project demonstrates how to implement a minimal vector library in Python using three different native extension methods:
- by_ctypes: C library loaded via Python's
ctypes
- by_python_c_api: C extension using the Python C API
- by_pybind11: C++ library exposed via
pybind11
Each approach provides a Vector
class supporting element-wise addition and subtraction.
by_ctypes/
minimal_numpy.c # C implementation of vector operations
minimal_numpy.py # Python wrapper using ctypes
Makefile # Build shared library
by_python_c_api/
minimal_numpy.c # C extension using Python C API
setup.py # Build script
test.py # Usage example
README.md # Approach-specific instructions
by_pybind11/
minimal_numpy.cpp # C++ implementation with pybind11 bindings
setup.py # Build script
test.py # Usage example
README.md # Approach-specific instructions
Build:
cd by_ctypes
make run
See their respective README.md
files for build and run instructions.
Vector
class: stores a list of doubles- Supports
+
and-
operators for element-wise addition/subtraction - Type and size checks for safe operations
- Demonstrates three native extension techniques
- Checked for AVX instruction usage in compiled libraries
We run size = 1000000
and repetition = 50
for addition and subtraction benchmarks.
10 warm-up runs are performed before timing to ensure fair measurements.
Here is a summary of the results (lower is better):
Method | Addition Time (s) | Subtraction Time (s) |
---|---|---|
by_ctypes | 2.4886 | 2.4444 |
by_python_c_api | 0.0171 | 0.0170 |
by_pybind11 | 0.0392 | 0.0389 |
numpy_reference | 0.0203 | 0.0208 |
For clangd user, just run pkg-config --cflags python3
to get the necessary include paths and add them to .clangd
: