Python Performance Tips, Part 2 - Python Performance 3 of n

转载 2013年12月04日 11:46:41

Python Performance Tips, 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.

  1. 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?
  2. 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”
    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.
  3. 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!)
  4. Use third-party packages.
    There are many high-performance libraries and tools designed for Python. Here is a short list of useful acceleration packages.

  5. 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 threadslifting 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. 

  6. 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


Chinese version

Python Performance 2 of n - Python Performance Tips, Part 1

Two good articles talking the performance for Python. Bookmark them here.
  • 2012年10月28日 14:49
  • 490

Android性能优化之Performance Tips

  • sdkfjksf
  • sdkfjksf
  • 2016年04月26日 11:01
  • 9720

High Performance Python 笔记(Python是门不错的语言,全栈程序员就用它好了!)

High Performance Python 目录 1 Understanding Performant Python2 Profiling3 Lists and Tuples4 Di...
  • cteng
  • cteng
  • 2014年10月07日 22:48
  • 2165

基于python 的性能测试工具

Pylot - Python Load Tester Multi-Mechanize - Performance Test Framework in Python locust - easy ...
  • u011546806
  • u011546806
  • 2015年06月05日 10:25
  • 375

6 Python Performance Tips

from: Python is such a cool langua...
  • longxibendi
  • longxibendi
  • 2015年02月10日 13:36
  • 730

Python Performance Tips

Part 1 To read the Zen of Python, type import this in your Python interpreter. A sharp reader n...
  • colinsun
  • colinsun
  • 2012年05月18日 11:19
  • 1229

Benchmark of Python WSGI Servers

Benchmark of Python WSGI Servers Nicholas Piël | March 15, 2010 It has been a while since the ...
  • 2014年05月01日 22:48
  • 1346

python 性能分析与个人实践

  • gningh
  • gningh
  • 2016年11月23日 15:16
  • 974

如何分析Performance Monitor (PerfMon) Log

  Windows 2003 和xp提供了性能监视器的几个命令行工具,他们是logman utility (logman.exe),relog utility (relog.exe) 和type...
  • shanyou
  • shanyou
  • 2008年06月17日 18:44
  • 1203

Python performance 1 of n

If you would like to improve the running performance of Python, try 1) Use profile/cProfile to bench...
  • 2012年09月25日 22:43
  • 346
您举报文章:Python Performance Tips, Part 2 - Python Performance 3 of n