Convert Python program to C/C++ code?


is it possible to convert a Python program to C/C++?

I need to implement a couple of algorithms, and I'm not sure if the performance gap is big enough to justify all the pain I'd go through when doing it in C/C++ (which I'm not good at). I thought about writing one simple algorithm and benchmark it against such a converted solution. If that alone is significantly faster than the Python version, then I'll have no other choice than doing it in C/C++.

8/5/2015 5:45:13 PM

Accepted Answer

Yes. Look at Cython. It does just that: Converts Python to C for speedups.

1/10/2011 6:56:18 PM

If the C variant needs x hours less, then I'd invest that time in letting the algorithms run longer/again

"invest" isn't the right word here.

  1. Build a working implementation in Python. You'll finish this long before you'd finish a C version.

  2. Measure performance with the Python profiler. Fix any problems you find. Change data structures and algorithms as necessary to really do this properly. You'll finish this long before you finish the first version in C.

  3. If it's still too slow, manually translate the well-designed and carefully constructed Python into C.

    Because of the way hindsight works, doing the second version from existing Python (with existing unit tests, and with existing profiling data) will still be faster than trying to do the C code from scratch.

This quote is important.

Thompson's Rule for First-Time Telescope Makers
It is faster to make a four-inch mirror and then a six-inch mirror than to make a six-inch mirror.

Bill McKeenan
Wang Institute

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow