MST

星途 面试题库

面试题:Python中使用pytest进行性能测试:如何配置pytest以收集性能指标

在Python项目中使用pytest进行性能测试,你需要配置pytest收集性能指标数据。请说明你会使用哪些插件(如果有)以及如何配置这些插件来实现这一目标,给出关键的代码示例和配置步骤。
49.5万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
  1. 使用的插件
    • pytest - benchmark插件,它可以帮助我们测量Python代码的性能,并收集性能指标数据。
  2. 安装插件: 使用pip install pytest - benchmark进行安装。
  3. 关键代码示例
    import pytest
    
    
    def func_to_benchmark():
        result = 0
        for i in range(1000):
            result += i
        return result
    
    
    def test_func_benchmark(benchmark):
        result = benchmark(func_to_benchmark)
        assert result == 499500
    
  4. 配置步骤
    • 命令行运行:直接在项目根目录下运行pytest命令,pytest - benchmark插件会自动收集性能指标数据。例如,运行上述测试代码,在命令行中输入pytest,它会输出类似如下信息:
      ========================= test session starts ==========================
      platform linux -- Python 3.8.10, pytest - 7.4.0, pluggy - 1.3.0
      rootdir: /your_project_path
      plugins: benchmark - 4.0.0
      collected 1 item
      
      test_performance.py.F                                                   [100%]
      
      =========================== FAILURES ===========================
      _____________________ test_func_benchmark ______________________
      
      benchmark = <pytest_benchmark.fixture.BenchmarkFixture object at 0x7f8c2c0f4430>
      
          def test_func_benchmark(benchmark):
              result = benchmark(func_to_benchmark)
      >       assert result == 499500
      E       assert 0 == 499500
      
      test_performance.py:10: AssertionError
      ------------------------- benchmark: 1 tests ------------------------
      Name (time in ms)         Min                Max                Mean             StdDev             Median               IQR            Outliers  OPS (Kops/s)            Rounds  Iterations
      ----------------------------------------------------------------------------------------------------------------------------
      test_func_benchmark     0.0260 (1.0)      0.0448 (1.0)      0.0311 (1.0)      0.0054 (1.0)      0.0280 (1.0)      0.0037 (1.0)      1;0      32.1566 (1.0)           30           1
      ==========================================================================================
      1 failed in 0.11s
      
    • 配置文件:如果需要更多自定义配置,可以在pytest.inisetup.cfg文件中添加配置。例如在pytest.ini文件中:
      [pytest]
      addopts = --benchmark - groupby=func
      
      这里--benchmark - groupby=func表示按函数分组显示性能数据,你可以根据实际需求调整配置选项。