我在 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
结果:
0.2561519145965576
所以从上面的代码我可以找到代码的执行时间,但是如何在python中找到代码的统计信息?
最后我的意图是以下几点
- 如何在python中找到代码的统计信息
- 如何在python中查找整段代码的执行时间
- 代码统计实际上意味着什么?
编辑代码:
例如我在文件 test.py
现在我已经用下面的命令运行了上面的文件
python -m cProfile test.py
结果:
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}
所以当我运行上面的代码时我需要这样的东西,我正在尝试的是在文件 test.py
中编写打印统计信息的功能,而不是使用命令 运行文件>python -m cProfile test.py
来自终端。
至少我想在文件运行时找到函数 calculation()
的统计信息和执行时间,因为实际上函数计算具有执行某些操作的强大功能。
最佳答案
看来您要问的是如何使用 timeit 模块的编程接口(interface)。记录在案 here .您将需要一个样本集来计算统计信息,例如最小值、最大值、平均值等,这意味着通过 timeit 模块中包含的 Timeit 类的 repeat 方法运行多次计算。
例如:
timer = timeit.Timer(calculation)
results = timer.timeit(10000)
关于python - 如何在python中查找代码的统计信息和执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13374201/