Python怎么测量性能?用什么方法优化代码执行速度?

文章导读
Previous Quiz Next 同一个问题可能有多种算法来解决。因此,我们需要优化解决方案的性能。Python 的 timeit 模块是一个有用的工具,用于测量 Python 应用程序的性能。
A A

Python - 性能测量



Previous
Quiz
Next

同一个问题可能有多种算法来解决。因此,我们需要优化解决方案的性能。Python 的 timeit 模块是一个有用的工具,用于测量 Python 应用程序的性能。

该模块中的 timeit() 函数用于测量 Python 代码的执行时间。

语法

timeit.timeit(stmt, setup, timer, number)

参数

  • stmt − 用于测量性能的代码片段。

  • setup − 要传递的设置细节参数或变量。

  • timer − 使用默认 timer,因此可以省略。

  • number − 代码将被执行的次数。默认为 1000000。

示例

以下语句使用列表推导式返回范围 0 到 100 内每个数字的 2 倍的列表。

>>> [n*2 for n in range(100)]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34,
36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68,
70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100,
102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126,
128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152,
154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178,
180, 182, 184, 186, 188, 190, 192, 194, 196, 198]

要测量上述语句的执行时间,我们使用以下 timeit() 函数 −

>>> from timeit import timeit
>>> timeit('[n*2 for n in range(100)]', number=10000)
0.0862189000035869

将执行时间与使用 for 循环追加数字的过程进行比较。

>>> string = '''
... numbers=[]
... for n in range(100):
... numbers.append(n*2)
... '''
>>> timeit(string, number=10000)
0.1010853999905521

结果显示列表推导式更高效。

语句字符串可以包含一个 Python 函数,并可以通过 setup 代码传递一个或多个参数。

我们将比较使用循环的阶乘函数与其递归版本的执行时间。

使用 for 循环的普通函数 −

def fact(x):
   fact = 1
   for i in range(1, x+1):
      fact*=i
   return fact

递归阶乘的定义。

def rfact(x):
   if x==1:
      return 1
   else:
      return x*fact(x-1)

测试这些函数计算 10 的阶乘。

print ("Using loop:",fact(10))
print ("Using Recursion",rfact(10))
Result
Using loop: 3628800
Using Recursion 3628800

现在我们使用 timeit() 函数找出它们的各自执行时间。

import timeit

setup1="""
from __main__ import fact
x = 10
"""

setup2="""
from __main__ import rfact
x = 10
"""

print ("Performance of factorial function with loop")
print(timeit.timeit(stmt = "fact(x)", setup=setup1, number=10000))

print ("Performance of factorial function with Recursion")
print(timeit.timeit(stmt = "rfact(x)", setup=setup2, number=10000))

输出

Performance of factorial function with loop
0.00330029999895487
Performance of factorial function with Recursion
0.006506800003990065

递归函数比使用循环的函数慢。

通过这种方式,我们可以对 Python 代码进行性能测量。