博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python性能鸡汤
阅读量:4312 次
发布时间:2019-06-06

本文共 8646 字,大约阅读时间需要 28 分钟。

To read the , 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  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 out. 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 . 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:

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.

转载于:https://www.cnblogs.com/chu888chu888/archive/2012/07/19/2599191.html

你可能感兴趣的文章
并查集
查看>>
sessionStorage
查看>>
代码示例_进程
查看>>
Java中关键词之this,super的使用
查看>>
人工智能暑期课程实践项目——智能家居控制(一)
查看>>
前端数据可视化插件(二)图谱
查看>>
kafka web端管理工具 kafka-manager【转发】
查看>>
获取控制台窗口句柄GetConsoleWindow
查看>>
Linux下Qt+CUDA调试并运行
查看>>
51nod 1197 字符串的数量 V2(矩阵快速幂+数论?)
查看>>
OKMX6Q在ltib生成的rootfs基础上制作带QT库的根文件系统
查看>>
zabbix
查看>>
多线程基础
查看>>
完美解决 error C2220: warning treated as error - no ‘object’ file generated
查看>>
使用SQL*PLUS,构建完美excel或html输出
查看>>
前后台验证字符串长度
查看>>
《算法导论 - 思考题》7-1 Hoare划分的正确性
查看>>
win64 Python下安装PIL出错解决2.7版本 (3.6版本可以使用)
查看>>
获取各种类型的节点
查看>>
表达式求值-201308081712.txt
查看>>