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.

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.

目录
相关文章
|
24天前
|
机器学习/深度学习 Python
堆叠集成策略的原理、实现方法及Python应用。堆叠通过多层模型组合,先用不同基础模型生成预测,再用元学习器整合这些预测,提升模型性能
本文深入探讨了堆叠集成策略的原理、实现方法及Python应用。堆叠通过多层模型组合,先用不同基础模型生成预测,再用元学习器整合这些预测,提升模型性能。文章详细介绍了堆叠的实现步骤,包括数据准备、基础模型训练、新训练集构建及元学习器训练,并讨论了其优缺点。
43 3
|
27天前
|
存储 大数据 Python
利用Python的高级语法优化代码可以显著提高代码的可读性、简洁性和性能
利用Python的高级语法优化代码可以显著提高代码的可读性、简洁性和性能
32 1
|
28天前
|
调度 数据库 Python
掌握Python中的异步编程,提升I/O密集型任务的性能
掌握Python中的异步编程,提升I/O密集型任务的性能
39 0
|
2月前
|
测试技术 持续交付 Apache
性能怪兽来袭!Python+JMeter+Locust,让你的应用性能飙升🦖
【10月更文挑战第10天】随着互联网应用规模的不断扩大,性能测试变得至关重要。本文将探讨如何利用Python结合Apache JMeter和Locust,构建高效且可定制的性能测试框架。通过介绍JMeter和Locust的使用方法及Python的集成技巧,帮助应用在高负载下保持稳定运行。
73 2
|
2月前
|
机器学习/深度学习 数据挖掘 Serverless
手把手教你全面评估机器学习模型性能:从选择正确评价指标到使用Python与Scikit-learn进行实战演练的详细指南
【10月更文挑战第10天】评估机器学习模型性能是开发流程的关键,涉及准确性、可解释性、运行速度等多方面考量。不同任务(如分类、回归)采用不同评价指标,如准确率、F1分数、MSE等。示例代码展示了使用Scikit-learn库评估逻辑回归模型的过程,包括数据准备、模型训练、性能评估及交叉验证。
120 1
|
2月前
|
存储 数据处理 Python
深入解析Python中的生成器:效率与性能的双重提升
生成器不仅是Python中的一个高级特性,它们是构建高效、内存友好型应用程序的基石。本文将深入探讨生成器的内部机制,揭示它们如何通过惰性计算和迭代器协议提高数据处理的效率。
|
2月前
|
缓存 并行计算 算法
如何提高 Python 高阶函数的性能?
【10月更文挑战第2天】
20 3
|
2月前
|
测试技术 持续交付 Apache
性能怪兽来袭!Python+JMeter+Locust,让你的应用性能飙升🦖
【10月更文挑战第2天】随着互联网应用规模的不断膨胀,性能测试变得至关重要。本文将介绍如何利用Python结合Apache JMeter和Locust构建高效且可定制的性能测试框架。Apache JMeter是一款广泛使用的开源负载测试工具,适合测试静态和动态资源;Locust则基于Python,通过编写简单的脚本模拟HTTP请求,更适合复杂的测试场景。
72 3
|
2月前
|
安全 数据安全/隐私保护 UED
优化用户体验:前后端分离架构下Python WebSocket实时通信的性能考量
在当今互联网技术的迅猛发展中,前后端分离架构已然成为主流趋势,它不仅提升了开发效率,也优化了用户体验。然而,在这种架构模式下,如何实现高效的实时通信,特别是利用WebSocket协议,成为了提升用户体验的关键。本文将探讨在前后端分离架构中,使用Python进行WebSocket实时通信时的性能考量,以及与传统轮询方式的比较。
74 2
|
2月前
|
数据处理 Python
如何优化Python读取大文件的内存占用与性能
如何优化Python读取大文件的内存占用与性能
192 0
下一篇
DataWorks