使用 pytest 進行效能測試

Python 測試入門

Alexander Levin

Data Scientist

什麼是效能測試

效能(Performance):軟體為完成任務時,對系統資源的使用效率。

效能測試(Performance Testing):量測軟體效能的一種測試。

Python 測試入門

何時需要效能測試

資源:

  • 執行時間
  • CPU
  • RAM
  • 其他資源

情境:

  • 網站速度最佳化
  • App 承載百萬請求
  • 掃地機器人路徑規劃
Python 測試入門

Benchmark fixture

安裝:

pip install pytest-benchmark
# Example_1.py
import time
def test_func(benchmark):
    benchmark(time.sleep, 1)

CLI 指令:

pytest Example_1.py
Python 測試入門

效能量測結果

執行上述 CLI 指令後的結果: 執行 pytest 後的效能量測結果

time.sleep(1) 改為 time.sleep(3)將程式中的 time-dot sleep 從 1 改為 3 後的效能量測結果

Python 測試入門

Benchmark 裝飾器

# Example_2.py
import time
def test_func(benchmark):
    @benchmark
    def sleep_for_1_sec():
        time.sleep(1)

CLI 指令:

pytest Example_2.py
Python 測試入門

重點整理

  • 效能測試:量測軟體效能的測試。
  • 資源通常有限。
  • 在資源受限時特別有用。
  • 使用 pytest-benchmark 的方式:
    • 直接呼叫 benchmark
    • @benchmark 作為裝飾器
  • 結果以秒描述多次量測的樣本。
Python 測試入門

一起來練習吧!

Python 測試入門

Preparing Video For Download...