萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 函式執行計時裝飾器:從入門到 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 確保計時即使拋異常也能印出。
  • 統計聚合:累積呼叫次數、總耗時、最大/最小值,定期或程式結束時輸出報表。
  • 整合 logging:替換 print 為 logger.debug,支援等級控制、檔案輪轉。
  • 非同步支援:檢測 asyncio.iscoroutinefunction 回傳 async def _wrapper。

生產級替代方案

  • cProfile:標準庫完整分析器,python -m cProfile script.py。
  • pyinstrument:統計式取樣,低開銷,適合生產環境。
  • line_profiler:逐行耗時分析,@profile 裝飾器。

自製裝飾器適合輕量級、特定函式的快速觀測;系統級效能調優請上專業工具。兩者互補,構建完整可觀測體系。

copyright © 萬盛學電腦網 all rights reserved