This project demonstrates how to accelerate Python with C++ by implementing the Sieve of Eratosthenes in both languages and comparing their performance.
Running sieve up to 200,000,000:
➡️ The C++ version is about 16x faster than pure Python while producing the same result.
sieve.cppimplements the prime sieve in C++.- The C++ code is compiled into a shared library (
.soon Linux/macOS,.dllon Windows). main.pyloads the library usingctypes, runs the sieve, and compares performance with a pure Python implementation.
g++ -O3 -shared -fPIC sieve.cpp -o libsieve.sog++ -O3 -shared -o sum_squares.dll sum_squares.cppThe sieve.cpp file uses extern "C" to ensure compatibility between C++ and Python's ctypes module. Here's why:
- C++ Name Mangling: C++ compilers modify function names (a process called name mangling) to support function overloading and other C++ features. This makes it difficult for
ctypesto find the exact function name in the compiled shared library. - C-Style Linkage: By wrapping the function declaration in
extern "C", we instruct the C++ compiler to use C-style linkage, which disables name mangling. This ensures the function name in the shared library (e.g.,sieve) matches whatctypesexpects when calling it from Python. - Interoperability:
extern "C"makes the C++ function accessible to Python'sctypesas if it were a C function, simplifying the integration process.
Without extern "C", the function name in the compiled library would be mangled (e.g., something like _Z5sieveiPiS_), causing ctypes to fail when trying to call sieve.