python运行时间的几种方法
Python  /  管理员 发布于 7年前   213
最早见过手写的,类似于下面这种:
import datetime def time_1(): begin = datetime.datetime.now() sum = 0 for i in xrange(10000000): sum = sum + i end = datetime.datetime.now() return end-beginprint time_1()
输出如下:
➜ Python python time_1.py
0:00:00.280797
另外一种方法是使用timeit模块,使用方法如下:
In [5]: import timeitIn [6]: timeit.timeit("sum(range(100))")Out[6]: 1.2272648811340332
还可以在命令行上使用这种timeit模块,如下:
➜ Python python -m timeit -s"import time_1 as t" "t.time_1()"0:00:00.28204410 loops, best of 3: 279 msec per loop
注意:timeit模块会多次运行程序以获得更精确的时间,所以需要避免重复执行带来的影响。比方说x.sort()这种操作,因为第一次执行之后,后边已经是排好的了,准确性就收到了影响。
还有一种方法是使用cProfile模块,代码如下,名字为time_1.py:
import datetime def time_1(): begin = datetime.datetime.now() sum = 0 for i in xrange(10000000): sum = sum + i end = datetime.datetime.now() return end-begin if __name__ == '__main__': print time_1()import cProfile cProfile.run('time_1()')
运行程序结果如下:
➜ Python python time_1.py0:00:00.282828 2 function calls in 0.000 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 <string>:1(<module>) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}Traceback (most recent call last): File "time_1.py", line 15, in <module> cProfile.run('main()') File "/usr/lib/python2.7/cProfile.py", line 29, in run prof = prof.run(statement) File "/usr/lib/python2.7/cProfile.py", line 135, in run return self.runctx(cmd, dict, dict) File "/usr/lib/python2.7/cProfile.py", line 140, in runctx exec cmd in globals, locals File "<string>", line 1, in <module>NameError: name 'main' is not defined➜ Python vi time_1.py➜ Python python time_1.py0:00:00.284642 5 function calls in 0.281 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.281 0.281 <string>:1(<module>) 1 0.281 0.281 0.281 0.281 time_1.py:3(time_1) 2 0.000 0.000 0.000 0.000 {built-in method now} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
一开始代码里最后一行写的是cProfile.run('main()'),提示没有main(),将main()改成函数名字就可以了。
以上就是本文的全部内容,希望对大家学习python程序设计有所帮助。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号