11

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?

Joseph Quinsey
  • 9,553
  • 10
  • 54
  • 77
  • 14
    C++ isn't a magic tool that makes everything faster. You can easily write C++ code that runs slower than python code doing the same thing. It always depends on your situation and your C++ skills, so the only real way to find it out is to do it. – PlasmaHH Mar 21 '13 at 09:39
  • It depends. You can make some code faster by replacing it with C++ but it is not guaranteed. – wRAR Mar 21 '13 at 09:39
  • Thank you for your responses!! Yes, everything comes down to individual programming skills. I just wanted to know if embedding c++ functions in your application could make your program faster. – Rushabh RajeshKumar Padalia Mar 21 '13 at 09:45
  • 1
    For instance, for short numerical code with many loop iterations, C++ will often be faster. For heavy input/output (files, network), it's often not worth the effort. – Antoine Mar 21 '13 at 09:50
  • 3
    @RushabhRajeshKumarPadalia: C++ is more CPU/memory efficient than Python... so if you are I/O bound (disk/database), it won't help much, whereas if you perform a lot of computations, it might if you do it right. Note that a number of specific Python libraries already exist as thin wrappers above C libraries to perform the heavy-work. – Matthieu M. Mar 21 '13 at 09:52

2 Answers2

7

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
3

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.

fortran
  • 74,053
  • 25
  • 135
  • 175