使用 pytest 进行性能测试

Python 测试入门

Alexander Levin

Data Scientist

什么是性能测试

性能(Performance):软件为完成任务对系统资源的利用效率。

性能测试(Performance Testing):度量软件性能的测试类型。

Python 测试入门

何时需要性能测试

资源:

  • 执行时间
  • CPU
  • 内存(RAM)
  • 其他资源

场景:

  • 网站速度优化
  • 应用接收百万级请求
  • 扫地机器人的路径规划
Python 测试入门

Benchmark 基治

安装:

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 测试入门

Passons à la pratique !

Python 测试入门

Preparing Video For Download...