Skip to content

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🚀 Use C++ in Python: Prime Sieve Benchmark

This project demonstrates how to accelerate Python with C++ by implementing the Sieve of Eratosthenes in both languages and comparing their performance.


📌 Benchmark Results

Running sieve up to 200,000,000:

➡️ The C++ version is about 16x faster than pure Python while producing the same result.


🛠️ How It Works

  • sieve.cpp implements the prime sieve in C++.
  • The C++ code is compiled into a shared library (.so on Linux/macOS, .dll on Windows).
  • main.py loads the library using ctypes, runs the sieve, and compares performance with a pure Python implementation.

🚀 Build Instructions

Linux / macOS

g++ -O3 -shared -fPIC sieve.cpp -o libsieve.so

On Windows (with MSVC or MinGW):

g++ -O3 -shared -o sum_squares.dll sum_squares.cpp

🛠️ Why extern "C"?

The 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 ctypes to 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 what ctypes expects when calling it from Python.
  • Interoperability: extern "C" makes the C++ function accessible to Python's ctypes as 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.

About

Speed up Python with C++!

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages