10.10 性能度量 Performance Measurement

Some Python users develop a deep interest in knowing the relative performance between different approaches to the same problem. Python provides a measurement tool that answers those questions immediately.

有些用户对了解解决同一问题的不同方法之间的性能差异很感兴趣。Python 提供了一个度量工具,为这些问题提供了直接答案。

For example, it may be tempting to use the tuple packing and unpacking feature instead of the traditional approach to swapping arguments. The timeit module quickly demonstrates that the traditional approach is faster:

例如,使用元组封装和拆封来交换元素看起来要比使用传统的方法要诱人的多。 timeit 证明了传统的方法更快一些。

>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.60864915603680925
>>> Timer('a,b = b,a', 'a=1; b=2').timeit()
0.8625194857439773

In contrast to timeit's fine level of granularity, the profile and pstats modules provide tools for identifying time critical sections in larger blocks of code.

相对于 timeit 的细粒度,profilepstats 模块提供了针对更大代码块的时间度量工具。