面试题答案
一键面试- 使用的插件:
pytest - benchmark
插件,它可以帮助我们测量Python代码的性能,并收集性能指标数据。
- 安装插件:
使用
pip install pytest - benchmark
进行安装。 - 关键代码示例:
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
- 配置步骤:
- 命令行运行:直接在项目根目录下运行
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.ini
或setup.cfg
文件中添加配置。例如在pytest.ini
文件中:
这里[pytest] addopts = --benchmark - groupby=func
--benchmark - groupby=func
表示按函数分组显示性能数据,你可以根据实际需求调整配置选项。
- 命令行运行:直接在项目根目录下运行