2024-06-03|閱讀時間 ‧ 約 23 分鐘

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


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

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


分享至
成為作者繼續創作的動力吧!
利用簡單的程式範例,詳細及白話文的方式解釋
從 Google News 追蹤更多 vocus 的最新精選內容從 Google News 追蹤更多 vocus 的最新精選內容

發表回應

成為會員 後即可發表留言
© 2024 vocus All rights reserved.