python檢測函式執行時間用 巧用裝飾器

2021-10-06 23:57:16 字數 1112 閱讀 9565

眾所周知,python中的time模組可以獲取時間戳,然後得到程式片執行所消耗的時間。但靠時間戳相減得到執行時間對於大規模程式是比較卑微的,你得命名很多個變數名去記錄時間戳。這個時候,可以利用裝飾器來記錄時間。

本文介紹兩種方法,進行對比。

常規版:

from time import time

def run():

res = 0

for i in range(10000):

for j in range(10000):

res += 1

res -= 1

if __name__ == '__main__':

start = time() # 獲取函式開始的時間戳

run()

end = time() # 獲取函式結束的時間戳

print('time cost:', end-start) # 相減得到執行時間

decorator版:

from time import time  

def time_costing(func):

def core():

start = time()

func()

print('time costing:', time() - start)

return core

@time_costing

def run():

res = 0

for i in range(10000):

for j in range(10000):

res += 1

res -= 1

if __name__ == '__main__':

run()

用裝飾器測函式時間的優越性體現在,只需在任何函式前一行加@***就可以。實屬帥氣又方便,對於大規模程式的細節時間監測非常有用。乾淨又衛生。

裝飾器不太明白的同學請戳《python中的裝飾器》

hope it's useful to you, thanks.

Python控制函式執行時間

在某個flask專案在做後端介面時需要設定超時響應,因為介面中使用爬蟲請求了多個 響應時間時長時短。我需要設定乙個最大響應時間,時間內如果介面爬蟲沒跑完,直接返回請求超時。從網上了解到有兩種方法,廢話不多說直接上 import requests,datetime,time import thread...

函式執行時間計算

在最近的工作中,遇到了需要檢視某些函式執行具體時間的需求,現在分享給大家,如果有更好的改進,大家相互交流,這裡只做拋磚引玉的作用。既然要想計算時間,那麼就必須知道如何計算時間,這裡選用的計算時間的函式為 do gettimeofday returns the time of day in a tim...

C 函式執行時間

遞迴和迴圈執行時間比較 c 計算函式執行時間system.diagnostics.stopwatch或者system.datetime.now using system using system.collections.generic using system.diagnostics using s...