Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does embedding c++ code in python make your python application faster? [closed]

Does embedding c++ code in python using ctypes, boost.python, etc make your python application faster?

Suppose I am making an application in pygtk and I need some functions which need to be fast. So if I use c++ for certain tasks in my application will it be beneficial?

And what are other options to make python code faster?

like image 297
Rushabh RajeshKumar Padalia Avatar asked Mar 21 '13 09:03

Rushabh RajeshKumar Padalia


People also ask

How do I make my Python as fast as C?

Although C remains the master of speed in general, PyPy can beat C in some cases. “If you want your code to magically run faster, you should probably just use PyPy.” PyPy is less effective when our program is fast anyway or when most of the runtime is spent for calls to non-python libraries.

What makes Python slow?

In summary: code is slowed down by the compilation and interpretation that occurs during runtime. Compare this to a statically typed, compiled language which runs just the CPU instructions once compilated. It's actually possible to extend Python with compiled modules that are written in C.

Why does Python run slower than C?

Internally Python code is interpreted during run time rather than being compiled to native code hence it is a bit slower. Running of Python script v/s running of C/C++ code: Python: First it is compiled into Byte Code. This Byte Code is then interpreted and executed by the PVM (Python Virtual Machine).


2 Answers

Rewriting performance-critical parts of your code in C++ could be one option. To do this effectively, you first need to understand where the bottlenecks are. The best way to do this is probably to write everything in pure Python first, and then profile.

Another option might be to use PyPy.

Finally, if you find that the bottleneck is numerical computations, then NumPy is worth a look.

It is worth noting that if, for example, it turns out that your code is I/O-bound, then none of the above options are going to be of much help.

like image 85
NPE Avatar answered Oct 18 '22 21:10

NPE


It depends, there's not a definitive answer. If you write bad code in C++ it could be even slower than well written Python code.

Assuming that you can write good quality C++ code, you can expect speedups up to 20x in the performance critical parts.

As the other answer says, NumPy is a good option for numerical bottlenecks (if you think in matrix operations rather than loops!); and SciPy comes with weaver, that allows you to embed inline C++ and other goodies.

like image 42
fortran Avatar answered Oct 18 '22 21:10

fortran