一个给定的问题可能由多个替代算法来解决。因此,我们需要优化解决方案的性能。Python 的 timeit 模块是衡量 Python 应用程序性能的有用工具。
此模块中的 timit() 函数测量 Python 代码的执行时间。
语法
timeit.timeit(stmt, setup, timer, number)
参数
- stmt - 用于衡量性能的代码片段。
- setup − setup details 要传递的参数或变量。
- timer − 使用默认计时器,因此可以跳过它。
- number − 代码将执行此次数。默认值为 1000000。
以下语句使用列表推导式为最大 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 函数,一个或多个参数 My 将作为设置代码传递给该函数。
我们将找到并使用循环的阶乘函数与其递归版本的执行时间进行比较。
使用 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
0.00330029999895487
Performance of factorial function with Recursion
0.006506800003990065
递归函数比 with loop 函数慢。
通过这种方式,我们可以对 Python 代码进行性能测量。