欢迎来到山村网

Python中统计函数运行耗时的方法

2019-03-02 12:22:50浏览:338 来源:山村网   
核心摘要:  本文实例讲述了Python中统计函数运行耗时的方法。分享给大家供大家参考。具体实现方法如下:  ? 123456789101112131415161

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

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 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

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

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 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中变量的拷贝和作用域问题

  • 信息二维码

    手机看新闻

  • 分享到
打赏
免责声明
• 
本文仅代表作者个人观点,本站未对其内容进行核实,请读者仅做参考,如若文中涉及有违公德、触犯法律的内容,一经发现,立即删除,作者需自行承担相应责任。涉及到版权或其他问题,请及时联系我们 xfptx@outlook.com