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

閱讀時間約 1 分鐘


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

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


52會員
112內容數
Python程式設計師,不是在學習就是在學習的路上
留言0
查看全部
發表第一個留言支持創作者!
從 Google News 追蹤更多 vocus 的最新精選內容