如何在python中查找代码的统计信息和执行时间
发布时间:2020-12-20 13:31:14 所属栏目:Python 来源:网络整理
导读:我正在研究 python,并遇到了一些查找代码统计和执行时间的概念 假设我有以下代码 from time import gmtime,strftimeimport timeitdef calculation(): a = 2 b = 3 res = a + b return resif 'name' == 'main' : exec_time = timeit.timeit(calculation) prin
我正在研究
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从终端运行该文件. 至少我想在文件运行时找到函数calculate()的统计和执行时间,因为实际上函数计算具有执行某些操作的大功能. 解决方法
看来你问的是如何使用timeit模块的编程接口.记录
here.您需要一个样本集来计算统计数据,例如min,max,average等,这意味着通过timeit模块中包含的Timeit类的repeat方法运行多次计算.
例如: timer = timeit.Timer(calculation) results = timer.timeit(10000) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |