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

相关文章

Python基础语言学习笔记总结(精华)

Python基础语言学习笔记总结(精华)

以下是Python基础学习内容的学习笔记的全部内容,非常的详细,如果你对Python语言感兴趣,并且针对性的系统学习一下基础语言知识,下面的内容能够很好的满足你的需求,如果感觉不错,就收...

Python3.6使用tesseract-ocr的正确方法

Tesseract介绍 tesseract是一个挺不错的OCR引擎,目前的问题是最新的中文资料相对较少,过时、不准确的信息偏多。 tesseract是一个google支持的开源ocr项目...

微信跳一跳python自动代码解读1.0

微信跳一跳python自动代码解读1.0

微信跳一跳自动代码,具体内容如下 那个跳一跳python“外挂”,有几个python文件,其中有一个是得到截图,然后鼠标在图片上点击两次,python窗口上会打印两次鼠标的位置,并且会跟...

使用python实现个性化词云的方法

使用python实现个性化词云的方法

先上图片 词云图 需要模板 pip install jieba pip install wordcloud 还需要安装另外两个东西这两个我也不太懂借鉴百度写上去的 pi...

Python用imghdr模块识别图片格式实例解析

imghdr模块 功能描述:imghdr模块用于识别图片的格式。它通过检测文件的前几个字节,从而判断图片的格式。 唯一一个API imghdr.what(file, h=None) 第一...