我是一名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中找到代码的统计信息
- 如何找到整个代码的执行时间
- 什么是代码的统计信息?
编辑后的代码:
例如,我将以上代码保存在文件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()
的统计信息和执行时间,因为实际上函数calculation()
具有执行某些操作的重要功能。