Python中統計函數運行耗時的方法

來源:互聯網
上載者:User
本文執行個體講述了Python中統計函數運行耗時的方法。分享給大家供大家參考。具體實現方法如下:

import timedef 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_medef test(x, y):  time.sleep(0.1)@time_medef test2(x):  time.sleep(0.2)test(1, 2)test2(2)#輸出:#test cost 0.1001529524 second#test2 cost 0.199968431742 second

另一個更進階一點的版本是:

import timeimport functoolsdef 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程式設計有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.