Python性能鸡汤

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:

  1. 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.
  2. 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)
  3. 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
  4. Use local variable if possible:
    Python is faster retrieving a local variable than retrieving a global variable. That is, avoid the “global” keyword.
  5. Use “in” if possible:
    To check membership in general, use the “in” keyword. It is clean and fast.
    >>> for key in sequence:
    >>>     print “found”
  6. 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.
  7. 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
  8. 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]
  9. 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.
  10. 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
  11. 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)]
  12. 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.
  13. 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. 
  14. 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 
  15. 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.
  16. 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.
  17. 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.
  18. 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.

时间: 2024-08-03 20:35:01

Python性能鸡汤的相关文章

如何进行 Python性能分析,你才能如鱼得水?

[编者按]本文作者为 Bryan Helmig,主要介绍 Python 应用性能分析的三种进阶方案.文章系国内 ITOM 管理平台 OneAPM 编译呈现. 我们应该忽略一些微小的效率提升,几乎在 97% 的情况下,都是如此:过早的优化是万恶之源.-- Donald Knuth 如果不先想想Knuth的这句名言,就开始进行优化工作,是不明智的.然而,有时你为了获得某些特性不假思索就写下了O(N^2) 这样的代码,虽然你很快就忘记它们了,它们却可能反咬你一口,给你带来麻烦:本文就是为这种情况而准备

【译】几个Python性能优化技巧

问题描述 Python是一门非常酷的语言,因为很少的Python代码可以在短时间内做很多事情,并且,Python很容易就能支持多任务和多重处理.Python的批评者声称Python性能低效.执行缓慢,但实际上并非如此:尝试以下6个小技巧,可以加快Pytho应用程序. **1.关键代码可以依赖于扩展包**Python使许多编程任务变得简单,但是对于很关键的任务并不总是提供最好的性能.使用C.C++或者机器语言扩展包来执行关键任务能极大改善性能.这些包是依赖于平台的,也就是说,你必须使用特定的.与你

利用 NGINX 最大化 Python 性能,第二部分:负载均衡和监控

[编者按]本文主要介绍 NGINX 的主要功能以及如何通过 Nginx 优化 Python 应用性能.本文系国内 ITOM 管理平台 OneAPM 编译呈现. 本文上一篇系: 利用 NGINX 最大化 Python 性能,第一部分:Web 服务和缓存. Python 以其高性能脚本语言而著称,而 NGINX 则能够通过增加代码的实际执行速度来提供助力.对于单一服务器来说,如果网页的一半由静态文件组成(很多网页都有一半由静态文件组成),增加静态文件缓存可使这类网页性能翻倍,缓存动态应用程序内容能够

Python性能提升之延迟初始化_python

所谓类属性的延迟计算就是将类的属性定义成一个property,只在访问的时候才会计算,而且一旦被访问后,结果将会被缓存起来,不用每次都计算.构造一个延迟计算属性的主要目的是为了提升性能 property 在切入正题之前,我们了解下property的用法,property可以将属性的访问转变成方法的调用. class Circle(object): def __init__(self, radius): self.radius = radius @property def area(self):

Python 性能优化技巧总结_python

1.使用测量工具,量化性能才能改进性能,常用的timeit和memory_profiler,此外还有profile.cProfile.hotshot等,memory_profiler用了psutil,所以不能跟踪cpython的扩展: 2.用C来解决费时的处理,c是效率的代名词,也是python用来解决效率问题的主要途径,甚至有时候我都觉得python是c的完美搭档.常用的是Cython,直接把py代码c化然后又能像使用py包一样使用,其次是ctypes,效率最最高的存在,最后还有CPython

Python 性能诊断及代码优化技巧

    程序代码的优化通常包含:减小代码的体积,提高代码的运行效率.这样可以让程序运行得更快.下面我们来具体谈谈 Python 代码优化常见技巧. 改进算法,选择合适的数据结构 一个良好的算法能够对性能起到关键作用,因此性能改进的首要点是对算法的改进.在算法的时间复杂度排序上依次是: O(1) -> O(lg n) -> O(n lg n) -> O(n^2) -> O(n^3) -> O(n^k) -> O(k^n) -> O(n!) 因此如果能够在时间复杂度上

Python性能优化经验之谈(翻译)

在微博上看到了一遍文章,然后就试着翻译了一下,有些地方看不懂,就直接贴原文了,还望能看懂的人指点一下. # 快速的Python性能优化 # 1.%timeit (per line) and %prun (cProfile) in ipython interactive shell. Profile your code while working on it, and try to find of where is the bottleneck. This is not contrary to t

Python性能优化

正文 注意:本文除非特殊指明,"python"都是代表CPython,即C语言实现的标准python,且本文所讨论的是版本为2.7的CPython. python为什么性能差: 当我们提到一门编程语言的效率时:通常有两层意思,第一是开发效率,这是对程序员而言,完成编码所需要的时间;另一个是运行效率,这是对计算机而言,完成计算任务所需要的时间.编码效率和运行效率往往是鱼与熊掌的关系,是很难同时兼顾的.不同的语言会有不同的侧重,python语言毫无疑问更在乎编码效率,life is sho

利用 NGINX 最大化 Python 性能,第一部分:Web 服务和缓存

[编者按]本文主要介绍 nginx 的主要功能以及如何通过 NGINX 优化 Python 应用性能.本文系国内 ITOM 管理平台 OneAPM 编译呈现. Python 的著名之处在于使用简单方便,软件开发简单,而且据说运行性能优于其它脚本语言.(虽然最新版本的 PHP.PHP 7 可能会与它展开激烈竞争.) 所有人都希望自己的网站和应用程序运行得更快一些.但是,每个网站在流量增长或骤然出现流量峰值时都很容易发生性能问题.甚至宕机(这一般会在服务器最繁忙的时候发生).此外在运行期间,无论是流