Part 1
To read the Zen of Python, type import this in your Python interpreter. A sharp reader new to Python will notice the word “interpreter”, and realize that Python is another scripting language. “It must be slow!”
No question about it: Python program does not run as fast or efficiently as compiled languages. Even Python advocates will tell you performance is the area that Python is not good for. However, YouTube has proven Python is capable of serving 40 million videos per hour. All you have to do is writing efficient code and seek external (C/C++) implementation for speed if needed. Here are the tips to help you become a better Python developer:
- Go for built-in functions:
You can write efficient code in Python, but it’s very hard to beat built-in functions (written in C). Check them outhere. They are very fast. - Use join() to glue a large number of strings:
You can use “+” to combine several strings. Since string is immutable in Python, every “+” operation involves creating a new string and copying the old content. A frequent idiom is to use Python’s array module to modify individual characters; when you are done, use the join() function to re-create your final string.
>>> #This is good to glue a large number of strings
>>> for chunk in input():
>>> my_string.join(chunk) - Use Python multiple assignment to swap variables:
This is elegant and faster in Python:
>>> x, y = y, x
This is slower:
>>> temp = x
>>> x = y
>>> y = temp - Use local variable if possible:
Python is faster retrieving a local variable than retrieving a global variable. That is, avoid the “global” keyword. - Use “in” if possible:
To check membership in general, use the “in” keyword. It is clean and fast.
>>> for key in sequence:
>>> print “found” - Speed up by lazy importing:
Move the “import” statement into function so that you only use import when necessary. In other words, if some modules are not needed right away, import them later. For example, you can speed up your program by not importing a long list of modules at startup. This technique does not enhance the overall performance. It helps you distribute the loading time for modules more evenly. - Use “while 1″ for the infinite loop:
Sometimes you want an infinite loop in your program. (for instance, a listening socket) Even though “while True” accomplishes the same thing, “while 1″ is a single jump operation. Apply this trick to your high-performance Python code.
>>> while 1:
>>> #do stuff, faster with while 1
>>> while True:
>>> # do stuff, slower with wile True - Use list comprehension:
Since Python 2.0, you can use list comprehension to replace many “for” and “while” blocks. List comprehension is faster because it is optimized for Python interpreter to spot a predictable pattern during looping. As a bonus, list comprehension can be more readable (functional programming), and in most cases it saves you one extra variable for counting. For example, let’s get the even numbers between 1 to 10 with one line:
>>> # the good way to iterate a range
>>> evens = [ i for i in range(10) if i%2 == 0]
>>> [0, 2, 4, 6, 8]
>>> # the following is not so Pythonic
>>> i = 0
>>> evens = []
>>> while i < 10:
>>> if i %2 == 0: evens.append(i)
>>> i += 1
>>> [0, 2, 4, 6, 8] - Use xrange() for a very long sequence:
This could save you tons of system memory because xrange() will only yield one integer element in a sequence at a time. As opposed to range(), it gives you an entire list, which is unnecessary overhead for looping. - Use Python generator to get value on demand:
This could also save memory and improve performance. If you are streaming video, you can send a chunk of bytes but not the entire stream. For example,
>>> chunk = ( 1000 * i for i in xrange(1000))
>>> chunk
<generator object <genexpr> at 0x7f65d90dcaa0>
>>> chunk.next()
0
>>> chunk.next()
1000
>>> chunk.next()
2000 - Learn itertools module:
The module is very efficient for iteration and combination. Let’s generate all permutation for a list [1, 2, 3] in three lines of Python code:
>>> import itertools
>>> iter = itertools.permutations([1,2,3])
>>> list(iter)
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)] - Learn bisect module for keeping a list in sorted order:
It is a free binary search implementation and a fast insertion tool for a sorted sequence. That is, you can use:
>>> import bisect
>>> bisect.insort(list, element)
You’ve inserted an element to your list, and you don’t have to call sort() again to keep the container sorted, which can be very expensive on a long sequence. - Understand that a Python list, is actually an array:
List in Python is not implemented as the usual single-linked list that people talk about in Computer Science. List in Python is, an array. That is, you can retrieve an element in a list using index with constant time O(1), without searching from the beginning of the list. What’s the implication of this? A Python developer should think for a moment when using insert() on a list object. For example:>>> list.insert(0, element)
That is not efficient when inserting an element at the front, because all the subsequent index in the list will have to be changed. You can, however, append an element to the end of the list efficiently using list.append(). Pick deque, however, if you want fast insertion or removal at both ends. It is fast because deque in Python is implemented as double-linked list. Say no more. - Use dict and set to test membership:
Python is very fast at checking if an element exists in a dicitonary or in a set. It is because dict and set are implemented using hash table. The lookup can be as fast as O(1). Therefore, if you need to check membership very often, use dict or set as your container..
>>> mylist = ['a', 'b', 'c'] #Slower, check membership with list:
>>> ‘c’ in mylist
>>> True
>>> myset = set(['a', 'b', 'c']) # Faster, check membership with set:
>>> ‘c’ in myset:
>>> True - Use sort() with Schwartzian Transform:
The native list.sort() function is extraordinarily fast. Python will sort the list in a natural order for you. Sometimes you need to sort things unnaturally. For example, you want to sort IP addresses based on your server location. Python supports custom comparison so you can do list.sort(cmp()), which is much slower than list.sort() because you introduce the function call overhead. If speed is a concern, you can apply the Guttman-Rosler Transform, which is based on the Schwartzian Transform. While it’s interesting to read the actual algorithm, the quick summary of how it works is that you can transform the list, and call Python’s built-in list.sort() -> which is faster, without using list.sort(cmp()) -> which is slower. - Cache results with Python decorator:
The symbol “@” is Python decorator syntax. Use it not only for tracing, locking or logging. You can decorate a Python function so that it remembers the results needed later. This technique is called memoization. Here is an example:
>>> from functools import wraps
>>> def memo(f):
>>> cache = { }
>>> @wraps(f)
>>> def wrap(*arg):
>>> if arg not in cache: cache['arg'] = f(*arg)
>>> return cache['arg']
>>> return wrap
And we can use this decorator on a Fibonacci function:
>>> @memo
>>> def fib(i):
>>> if i < 2: return 1
>>> return fib(i-1) + fib(i-2)
The key idea here is simple: enhance (decorate) your function to remember each Fibonacci term you’ve calculated; if they are in the cache, no need to calculate it again. - Understand Python GIL(global interpreter lock):
GIL is necessary because CPython’s memory management is not thread-safe. You can’t simply create multiple threads and hope Python will run faster on a multi-core machine. It is because GIL will prevents multiple native threads from executing Python bytecodes at once. In other words, GIL will serialize all your threads. You can, however, speed up your program by using threads to manage several forked processes, which are running independently outside your Python code. - Treat Python source code as your documentation:
Python has modules implemented in C for speed. When performance is critical and the official documentation is not enough, feel free to explore the source code yourself. You can find out the underlying data structure and algorithm. The Python repository is a wonderful place to stick around:http://svn.python.org/view/python/trunk/Modules
Conclusion:
There is no substitute for brains. It is developers’ responsibility to peek under the hood so they do not quickly throw together a bad design. The Python tips in this article can help you gain good performance. If speed is still not good enough, Python will need extra help: profiling and running external code. We will cover them both in the part 2 of this article.
Part 2
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
http://numpy.scipy.org - SciPy: another fast numerical processing library
http://scipy.org - GPULib: use your GPUs to speed up your code
http://txcorp.com/products/GPULib - PyPy: the just-in-time compiler to optimize your Python code
http://codespeak.net/pypy - Cython: translate Python code into C
http://cython.org - ShedSkin: translate Python code into C++
http://code.google.com/p/shedskin
- 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).
Conclusion:
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.
http://blog.monitis.com/index.php/2012/02/13/python-performance-tips-part-1/
http://blog.monitis.com/index.php/2012/03/21/python-performance-tips-part-2/
译文连接:
http://www.oschina.net/question/1579_45822
Python Wiki Tips:
http://wiki.python.org/moin/PythonSpeed/PerformanceTips