It’s a useful reminder that statically compiled code still matter. Just to name a few, Chrome, Firefox, MySQL, MS Office, and Photoshop are highly optimized software that many of us are using every day. Python, as an interpreted language, is not oblivious to this fact. Python alone cannot meet requirements in some domains where efficiency is a main priority. This is why Python supports infrastructure that touches the bare metal for you, by delegating heavy work to fast languages such as C. This is a critical feature for high-performance computing and embedded programming. Python Performance Tips Part 1 discussed how to use Python effectively. In part 2, we will cover profiling and extending Python.
- First, resist your temptation of optimization.
Optimization will introduce complexity to your code base. Check the following list before integrating with other languages. If your solution is “good enough”, optimizing is not necessarily good.
- Do your customers report speed problems?
- Can you minimize hard disk I/O access?
- Can you minimize network I/O access?
- Can you upgrade your hardware?
- Are you writing libraries for other developers?
- Is your third-party software up-to-date?
- Profile code with tools, not with intuition.
Speed problem can be subtle, so do not rely on intuition. Thanks to the “cprofiles” module, you can profile Python code by simply running
“python -m cProfile myprogram.py”
We wrote a test program (right). The profiling result is in the black box (above). The bottleneck here is the “very_slow()” function call. We can also see that “fast()” and “slow()” has been called 200 times each. This implies that if we can improve “fast()” and “slow()”, we will get a decent increase in performance. The cprofiles module can also be imported during runtime. This is useful for checking long-running processes.
- Review running-time complexity.
After profiling, give some basic analysis of how fast your solution is. Constant time is ideal. Logarithm algorithm is stable. Factorial solution will not scale.
O(1) -> O(lg n) -> O(n lg n) -> O(n^2) -> O(n^3) -> O(n^k) -> O(k^n) -> O(n!)
- Use third-party packages.
There are many high-performance libraries and tools designed for Python. Here is a short list of useful acceleration packages.
- NumPy: an open source equivalent to MatLab
- SciPy: another fast numerical processing library
- GPULib: use your GPUs to speed up your code
- PyPy: the just-in-time compiler to optimize your Python code
- Cython: translate Python code into C
- ShedSkin: translate Python code into C++
- NumPy: an open source equivalent to MatLab
- Use multiprocessing module for true concurrency.
Because GIL (Global Interpreter Lock) will serialize threads, multi-threading in Python cannot speed up your code in multiprocessor machines nor in machine cluster. Therefore Python offers a multiprocessing module which can spawn extra processes instead of threads, lifting the limitation imposed by GIL. Furthermore, you can combine this tip with external C code, to make your program even faster.
Note that a process is usually more expensive than a thread, since threads automatically share the same memory address space and file descriptors. This means that it will take more time to create a process, and likely cost more memory than creating a thread. This is something to consider if you plan to spawn many processes.
- Let’s go native.
So you’ve decided to use native code for performance. With the standard ctypes module, you can directly load compiled binary (.dll or .so files) into Python, without worrying about writing C/C++ code or build dependencies. For example, we wrote a program (on the right) that loads libc to generate random numbers.
However, the overhead of ctypes binding is not light. You should consider ctypes as a quick glue to your OS libraries or device drivers for accessing hardware. There are several libraries such as SWIG, Cython, and Boost Python that introduce much less calling overhead than ctypes does. Here we pick Boost Python library to inter-operate with Python, because Boost Python supports object-oriented features such as class and inheritance. As we can see from the example (on the right), we keep the usual C++ code (line 1~7), and then import it later (line 21~24). The major work here is to write a wrapper (line 10~18).
I hope the Python performance series has made you a better developer. At last, I would like to point out that while pushing performance to the limit is a fun game, premature optimization could turn it into a travesty. Python empowers you to interface with C-compatible languages seamlessly, but Python prefers development speed over executing speed with good reason. You have to ask yourself if users would pay extra for your hard-working hours on optimization. In addition, eliminating code readability just to save a few milliseconds almost never goes well. Developers in your team will always thank you for writing clean code. Stay close by the Python side, for life is short.
See also Python Performance Tips, Part 1