python运行时间的几种方法

yipeiwu_com5年前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-begin
print time_1()

输出如下: 

➜  Python python time_1.py

0:00:00.280797

另外一种方法是使用timeit模块,使用方法如下:

In [5]: import timeit
In [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.282044
10 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.py

0: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.py

0: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程序设计有所帮助。

相关文章

如何将你的应用迁移到Python3的三个步骤

Python 2.x 很快就要 失去官方支持 了,尽管如此,从 Python 2 迁移到 Python 3 却并没有想象中那么难。我在上周用了一个晚上的时间将一个 3D 渲染器的前端代码...

Python多继承顺序实例分析

本文实例讲述了Python多继承顺序。分享给大家供大家参考,具体如下: 示例1: #-*- coding:utf-8 -*- #!python2 class A(object):...

python文件读写操作与linux shell变量命令交互执行的方法

本文实例讲述了python文件读写操作与linux shell变量命令交互执行的方法。分享给大家供大家参考。具体如下: python对文件的读写还是挺方便的,与linux shell的交...

分享6个隐藏的python功能

小编在以前给大家介绍过python一些很少用到的功能,这次我们给大家分享了6个隐藏的python功能,学习下。 在python的设计哲学中,有这么一条内容:“Simple is bett...

利用Python如何实现一个小说网站雏形

前言 最近做了一个爬取妹子套图的小功能,小伙伴们似乎很有兴趣,为了还特意组建了一个Python兴趣学习小组,来一起学习。十个python九个爬,在大家的印象中好像Python只能做爬虫...