这篇文章主要为大家详细介绍了python运行时间的几种方法,分析每一种运行时间方法的利弊,感兴趣的小伙伴们可以参考一下
最早见过手写的,类似于下面这种:
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
立即学习“Python免费学习笔记(深入)”;
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 :1() 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 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 "", line 1, in 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 :1() 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程序设计有所帮助。
更多python运行时间的方法相关文章请关注PHP中文网!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2278413.html