python时间函数
来源:互联网 发布:免费阅读软件哪个好 编辑:程序博客网 时间:2024/05/17 23:23
出处:http://www.cnblogs.com/herbert/p/3395268.html
主要有以下三种方式:
一,CPU时间
time.clock()
测量CPU时间,比较精准,通过比较程序运行前后的CPU时间差,得出程序运行的CPU时间。
二, 时钟时间
time.time()
测量时钟时间,也就是通常的类似掐表计时。
三,基准时间
timeit.timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000)
简短示例:
timeit(“math.sqrt(2.0)”, “import math”)
timeit(“sqrt(2.0)”, “from ,math import sqrt”)
timeit(“test()”, “from __main__ import test”, number = 10000)
示例(示例中的三个方法都是求解一个数的因子数的个数)
CPU时间的示例:
import timedef countDiv(n): "Return the count number of divisors of n." count = 1 for i in range(1, n): if n%i == 0: count += 1 return countdef countDiv2(n): return len([x for x in range(1, n+1) if n%x == 0])def countDiv3(n): s = set() for i in range(1, n): if i in s: break else: if n%i == 0: s.update({i, n/i}) return len(s)start_CPU = time.clock()a = countDiv(73920)end_CPU = time.clock()print("Method 1: %f CPU seconds" % (end_CPU - start_CPU))start_CPU = time.clock()a = countDiv2(73920)end_CPU = time.clock()print("Method 2: %f CPU seconds" % (end_CPU - start_CPU))start_CPU = time.clock()a = countDiv3(73920)end_CPU = time.clock()print("Method 3: %f CPU seconds" % (end_CPU - start_CPU))
结果:最快的是方法三,方法二和方法一,其实不相上下.
Method 1: 0.022805 CPU secondsMethod 2: 0.015988 CPU secondsMethod 3: 0.000141 CPU seconds
时钟时间示例:
import timestart_Real = time.time()a = countDiv(73920)end_End = time.time()print("Method 1: %f real seconds" % (end_End - start_Real))start_Real = time.time()a = countDiv2(73920)end_End = time.time()print("Method 2: %f real seconds" % (end_End - start_Real))start_Real = time.time()a = countDiv3(73920)end_End = time.time()print("Method 3: %f real seconds" % (end_End - start_Real))
结果:
Method 1: 0.016001 real secondsMethod 2: 0.016001 real secondsMethod 3: 0.000000 real seconds
在精度不够的情况下,都无法得知,方法三真正的运行时间.
真的想知道,方法三比方法一或者二快多少倍,还是要使用timeit。timeit可以重复执行代码一定次数,这样更加稳定的反应程序的执行时间,不会因为一次的执行而产生较大的误差。
if __name__ == '__main__': import timeit print(timeit.timeit("countDiv(73920)", setup = "from __main__ import countDiv", number=100)) print(timeit.timeit("countDiv2(73920)", setup = "from __main__ import countDiv2", number=100)) print(timeit.timeit("countDiv3(73920)", setup = "from __main__ import countDiv3", number=100))
结果:
1.69929416825372461.690912806709730.013773491283526784
0 0
- python 时间函数
- python时间函数
- python 时间转换函数
- python时间处理函数
- Python时间函数
- python时间函数
- Python 时间处理函数
- Python日期时间函数
- Python日期时间函数
- Python日期时间函数
- Python日期时间函数
- Python日期时间函数
- Python日期时间函数
- Python的时间函数
- Python日期时间函数
- python时间函数
- python指定时间运行函数
- python中的时间函数编写
- 关于Android的查询CPU、流量、内存以及获取一个app的启动activity
- 如何从ncbi上下载sra数据
- ruby on rails中配置数据库,以及数据库与model层嫁接,增删改查详解
- java读取Excel数据,然后写入到txt文件,并批量保存到oracle数据库中
- js中cookie的使用详细分析
- python时间函数
- 数据中心的铜缆布线活力无限不过时
- Ubuntu系统配置samba服务
- 根据mimetype取扩展名
- java基础学习总结——equals方法
- 谈谈HBuilder以及HTML5+
- Java加密技术(一)——BASE64与单向加密算法MD5&SHA&MAC
- 使用Unity3D 自主实战开发的赛车游戏实例,关键点记录 (二)之地形场景漫游导览制作
- Spark组件之GraphX学习12--GraphX常见操作汇总SimpleGraphX