手机
当前位置:查字典教程网 >脚本专栏 >python >Python中统计函数运行耗时的方法
Python中统计函数运行耗时的方法
摘要:本文实例讲述了Python中统计函数运行耗时的方法。分享给大家供大家参考。具体实现方法如下:importtimedeftime_me(fn)...

本文实例讲述了Python中统计函数运行耗时的方法。分享给大家供大家参考。具体实现方法如下:

import time def time_me(fn): def _wrapper(*args, **kwargs): start = time.clock() fn(*args, **kwargs) print "%s cost %s second"%(fn.__name__, time.clock() - start) return _wrapper #这个装饰器可以在方便地统计函数运行的耗时。 #用来分析脚本的性能是最好不过了。 #这样用: @time_me def test(x, y): time.sleep(0.1) @time_me def test2(x): time.sleep(0.2) test(1, 2) test2(2) #输出: #test cost 0.1001529524 second #test2 cost 0.199968431742 second

另一个更高级一点的版本是:

import time import functools def time_me(info="used"): def _time_me(fn): @functools.wraps(fn) def _wrapper(*args, **kwargs): start = time.clock() fn(*args, **kwargs) print "%s %s %s"%(fn.__name__, info, time.clock() - start), "second" return _wrapper return _time_me @time_me() def test(x, y): time.sleep(0.1) @time_me("cost") def test2(x): time.sleep(0.2) test(1, 2) test2(2)

希望本文所述对大家的Python程序设计有所帮助。

【Python中统计函数运行耗时的方法】相关文章:

Python中的魔法方法深入理解

python爬取网站数据保存使用的方法

python操作日期和时间的方法

Python中apply函数的用法实例教程

python操作MySQL数据库的方法分享

Python中字典(dict)和列表(list)的排序方法实例

Python 用户登录验证的小例子

python生成器的使用方法

Python操作列表的常用方法分享

Python批量修改文件后缀的方法

精品推荐
分类导航