functools.wraps 進階版效能分析第一步:知道每個函式花多少時間。裝飾器讓計時邏輯與業務邏輯解耦,一行 @time_me 即可接入。本文提供兩個版本:基礎版與支援自定義標籤、保留原函式元資料的進階版。
import time
def time_me(fn):
def _wrapper(*args, **kwargs):
start = time.perf_counter() # 精度高於 time.clock()
fn(*args, **kwargs)
print(f"{fn.__name__} cost {time.perf_counter() - start:.6f} second")
return _wrapper
@time_me
def test(x, y):
time.sleep(0.1)
@time_me
def test2(x):
time.sleep(0.2)
test(1, 2) # test cost 0.100153 second
test2(2) # test2 cost 0.200012 second
⚠️ time.clock() 在 Python 3.3+ 棄用,3.8 移除,請改用 time.perf_counter()(高精度)或 time.process_time()(CPU 時間)。
functools.wraps + 可配置標籤)
import time
import functools
def time_me(info="used"):
'''帶參數裝飾器:info 為自定義標籤'''
def _time_me(fn):
@functools.wraps(fn) # 保留 __name__、__doc__、__module__ 等
def _wrapper(*args, **kwargs):
start = time.perf_counter()
fn(*args, **kwargs)
print(f"{fn.__name__} {info} {time.perf_counter() - start:.6f} second")
return _wrapper
return _time_me
@time_me() # 使用預設 "used"
def test(x, y):
time.sleep(0.1)
@time_me("cost") # 自定義標籤
def test2(x):
time.sleep(0.2)
test(1, 2) # test used 0.100153 second
test2(2) # test2 cost 0.200012 second
functools.wraps 為何重要?__name__、__doc__、__annotations__,讓 help()、除錯器、序列化、框架路由正常工作。wraps 時,test.__name__ 會變成 '_wrapper',導致日誌、追蹤混淆。return fn(*args, **kwargs) 而非丟棄結果。try/finally 確保計時即使拋異常也能印出。print 為 logger.debug,支援等級控制、檔案輪轉。asyncio.iscoroutinefunction 回傳 async def _wrapper。python -m cProfile script.py。@profile 裝飾器。自製裝飾器適合輕量級、特定函式的快速觀測;系統級效能調優請上專業工具。兩者互補,構建完整可觀測體系。