Shi*_*dla 6 python statistics execution-time
我正在研究 python,并遇到了一些查找代码的统计信息和执行时间的概念
假设我有以下代码
from time import gmtime, strftime
import timeit
def calculation():
a = 2
b = 3
res = a + b
return res
if 'name' == 'main' :
exec_time = timeit.timeit(calculation)
print exec_time
Run Code Online (Sandbox Code Playgroud)
结果:
0.2561519145965576
Run Code Online (Sandbox Code Playgroud)
所以从上面的代码我可以找到代码的执行时间,但是如何在python中找到代码的统计信息呢?
最后我的意图如下
编辑后的代码:
例如我的文件中有上面的代码test.py
现在我已经使用下面的命令运行了上面的文件
python -m cProfile test.py
Run Code Online (Sandbox Code Playgroud)
结果 :
sh-4.2$ python -m cProfile test.py
4 function calls in 0.001 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.001 0.001 0.001 0.001 test.py:1(<module>)
1 0.000 0.000 0.000 0.000 timeit.py:105(Timer)
1 0.001 0.001 0.001 0.001 timeit.py:53(<module>)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
Run Code Online (Sandbox Code Playgroud)
因此,当我运行上面的代码时,我需要类似的东西,我试图在文件中编写打印统计信息的功能,test.py而不是使用python -m cProfile test.py终端命令运行文件。
至少我想找到calculation()文件运行时函数的统计数据和执行时间,因为实际上函数计算具有执行某些操作的大功能。
看来您要问的是如何使用 timeit 模块的编程接口。此处记录了这一点。您需要一个样本集来计算统计数据,例如最小值、最大值、平均值等,这意味着通过 timeit 模块中包含的 Timeit 类的重复方法运行计算多次。
例如:
timer = timeit.Timer(calculation)
results = timer.timeit(10000)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4191 次 |
| 最近记录: |