萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 編程語言綜合 >> Python中統計函數運行耗時的方法

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

   本文實例講述了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程序設計有所幫助。

copyright © 萬盛學電腦網 all rights reserved