[Python][裝飾器]計算函式(CT)處理時間

更新於 發佈於 閱讀時間約 2 分鐘


在開發上,常常需要分析每一個函式處理時間,看是不是哪邊可以優化一下,把常用的功能包裝成裝飾器來做使用。

CT裝飾器

import time
def performance_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} 執行時間:{end_time - start_time} 秒")
return result
return wrapper

調用

@performance_decorator
def slow_function():
time.sleep(2)
print("Function executed")

slow_function()


詳細裝飾器介紹 在我另外一篇文章有提到

[Python基礎]淺談裝飾器 decorator


avatar-img
134會員
222內容數
本業是影像辨識軟體開發,閒暇時間進修AI相關內容,將學習到的內容寫成文章分享。
留言1
avatar-img
留言分享你的想法!

































































你可能也想看
從 Google News 追蹤更多 vocus 的最新精選內容