python中查看代码的运行时间方法
2017-07-25 17:33
405 查看
1. 使用装饰器来衡量函数执行时间
有一个简单方法,那就是定义一个装饰器来测量函数的执行时间,并输出结果:
import time from functools import wraps def fn_timer(function): @wraps(function) def function_timer(*args, **kwargs): t0 = time.time() result = function(*args, **kwargs) t1 = time.time() print ("Total time running %s: %s seconds" % (function.func_name, str(t1-t0)) ) return result return function_timer
接着,将这个装饰器添加到需要测量的函数之前,如下所示:
@fn_timer def myfunction(...): ...
例如,这里检测一个函数排序含有200万个随机数字的数组所需的时间:
@fn_timer def random_sort(n): return sorted([random.random() for i in range(n)]) if __name__ == "__main__": random_sort(2000000)
执行脚本时,会看到下面的结果:
Total time running random_sort: 1.41124916077 seconds
此方法的原文链接是10种检测Python程序运行时间、CPU和内存占用的方法
2. 使用time.time()函数
Python time time() 返回当前时间的时间戳(1970纪元后经过的浮点秒数)。
以下实例展示了 time() 函数的使用方法:
#!/usr/bin/python import time print "time.time(): %f " % time.time() print time.localtime( time.time() ) print time.asctime( time.localtime(time.time()) )
以上实例输出结果为:
time.time(): 1234892919.655932 (2009, 2, 17, 10, 48, 39, 1, 48, 0) Tue Feb 17 10:48:39 2009
使用time.time()查看代码的耗时
def getHomeData(request): starttime = time.time() #测试的代码前获取当前时间 try: hypervisors = api.nova.hypervisor_list(request) except Exception: hypervisors = [] exceptions.handle(request, _('Unable to retrieve hypervisor information.')) endtime1 = time.time() #测试的代码结束获取当前时间 timeall1 = endtime1 - starttime #得到代码的运行时间
总结:
1、方法一较适合方法的运行时间
2、方法二不仅能获取方法的运行时间,也能获取某几行代码运行的时间
相关文章推荐
- Java--查看某一段代码或方法运行时间的方法
- 转 Python获取代码运行时间的几种方法
- python测量代码运行时间方法
- python测量代码运行时间方法~
- Python 代码运行时间的3种计算方法
- vs2008查看函数运行时间的方法。
- C# 写个公共的测试代码运行时间的方法
- Python基于time模块求程序运行时间的方法
- 测试一段iOS代码运行时间的两种方法
- 查看mysql语句运行时间的2种方法
- python:查看程序运行时间
- 测试一段 iPhone 代码运行时间的方法
- 分别使用递归方法和非递归方法求斐波那契数列,并比较两者的运行速度(测量代码运行时间)
- 计算Python代码的运行时间
- 测量Python代码运行的时间
- Python几种建表方法运行时间的比较
- 三种计算Python的代码块或程序的运行时间的方法比较
- python中redis查看剩余过期时间及用正则通配符批量删除key的方法
- 转载:10种检测Python程序运行时间、CPU和内存占用的方法
- python运行时修改代码的方法——monkey patch