Python提供了许多方法来测量一段python代码的执行时间。一种方法是使用python内置时间模块并节省程序执行前后的时间?
当某些程序正在运行时,许多进程也会在后台运行,以使该代码可执行。时间模块不计算后台进程的执行时间,但是,如果需要精确的时间性能测量,可以使用timeit模块。
timeit模块将代码运行大约一百万次(默认值),并考虑了运行该代码所需的最短时间。
我们可以通过多种方式使用timeit模块。最简单的方法之一是直接在python CLI上使用。
我们将首先从timeit模块开始使用python CLI。使用CLI时,我们会注意到模块本身决定了对同一段代码执行的重复次数。
C:\Users\rajesh>python -m timeit "'-'.join(str(n) for n in range(200))" 1000 loops, best of 3: 290 usec per loop C:\Users\rajesh>python -m timeit "'-'.join(str(n) for n in range(200))" 1000 loops, best of 3: 292 usec per loop C:\Users\rajesh>python -m timeit "'-'.join(str(n) for n in range(200))" 1000 loops, best of 3: 294 usec per loop
接下来,我们通过另一个简单的示例介绍timeit,但是首先我们必须使用“ import timeit”语句导入timeit模块。如果我们不使用上面的命令行语法,这是必需的。
#Import timeit module import timeit # The instructions being timed. print('x' * 5) print('x' + 'x' + 'x' + 'x' + 'x') # Call timeit on the statements and print the time returned. # ... Specify optional number of iterations. print(timeit.timeit("y = 'x' * 3", number=10000000)) print(timeit.timeit("xy = 'x' + 'x' + 'x' + 'x' + 'x'", number = 10000000))
在上面,我们将带引号的字符串中的语句传递给timeit.timeit方法,然后通过指定数字参数来增加迭代次数。
输出结果
第一次运行上述程序时,生成的输出为:
xxxxx xxxxx 0.9041136896626635 0.7712796073957123
第二次运行以上程序,生成输出:
xxxxx xxxxx 0.7317015874427751 0.7312688195585995
第三次运行以上程序,生成输出:
xxxxx xxxxx 0.7240862411172824 0.7255863890794246
我们多次执行了上述程序(3次),发现执行时间有所减少。一个而不是手动执行的操作,让我们通过程序进行重复:
#Import timeit module import timeit # Call timeit on the statements and print the time returned. # ... Specify optional number of iterations. print(timeit.repeat("y = 'x' * 3", number=10000000, repeat = 5)) print() print(timeit.repeat("xy= 'x' + 'x' + 'x' + 'x' + 'x'", number = 10000000, repeat = 5))
输出结果
[0.7303736343436382, 0.7213687552991258, 0.7362311105941466, 0.7293136666273243, 0.7278277732068212] [0.7388334197158559, 0.7378481457977326, 0.9486733868277772, 0.735295442480929, 0.7398226849056382]
使用timeit模块运行多个语句:
我们可以在timeit模块中使用多个语句。我们使用分号分隔每个语句。虽然这不是编写代码的最佳方法,但有助于指定更长的代码片段。
#Import timeit module import timeit # Use semicolon for multiple statements. print(timeit.repeat("x = 2; x *= 2", number=100000000)) print(timeit.repeat("x = 1; x *= 4", number=100000000))
输出结果
[24.859605879029118, 23.58795536845994, 23.95826726353284] [22.70639977603264, 21.380195994245724, 20.71523588130414]
使用方法,在Timeit模块中进行设置:
通过指定设置参数,我们可以在timeit中使用自定义方法。在此参数中,我们指定了一个导入语句,该语句指示我们调用的方法。
#Import timeit module import timeit def func1(): return 1 def func2(): return sum([-1, 0, 1, 1]) # Test methods. print(func1()) print(func2()) # Pass setup argument to call methods. print(timeit.repeat("func1()", setup="from __main__ import func1")) print(timeit.repeat("func2()", setup="from __main__ import func2"))
在上面的程序中,我们针对func2()方法对func1()方法进行了基准测试。
输出结果
1 1 [0.44798489246658874, 0.4411512652046069, 0.44570416580426686] [1.583622557983199, 1.5712399227517881, 1.5469479030713984]
由于func1()减少了工作量,因此执行速度更快。
上面我们看到了如何使用timeit模块以及CLI和脚本来测量一小段python代码的性能。