You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PyTest/tox测试机器学习算法的运行速度?含lidtk示例

如何用PyTest/tox实现机器学习模型的速度测试?

当然可以用pytest-benchmark来实现你的需求,而且完全能区分开输入生成时间和模型预测时间——这一点很关键,毕竟我们要测的是模型本身的性能,不是数据生成的速度。下面我一步步给你讲怎么在lidtk里落地:

第一步:安装pytest-benchmark

首先确保你已经安装了这个插件:

pip install pytest-benchmark

如果用tox的话,记得把pytest-benchmark加到你的tox.ini的deps列表里,比如:

[testenv]
deps =
    pytest
    pytest-benchmark
commands = pytest tests/

第二步:编写测试用例,排除输入生成时间

pytest-benchmark允许你手动控制计时范围,完美跳过输入生成的耗时。核心思路是:

  1. 提前生成好测试输入(这部分不计时)
  2. 仅对classifier_predict的调用过程计时
  3. 设置最大允许时间,超时就标记测试失败

给你写个实际可运行的测试代码示例,替换你之前的伪代码:

import pytest
from your_lidtk_module import classifier_predict  # 替换成lidtk里的实际模块路径

def input_generator():
    # 这里写你的输入生成逻辑,比如生成符合模型要求的随机特征/文本
    return some_valid_input_features

def test_classifier_predict_speed(benchmark):
    # 先生成输入,这部分不参与计时
    test_input = input_generator()
    
    # 用benchmark只测classifier_predict的执行时间
    result = benchmark(classifier_predict, test_input)
    
    # 可选:顺便验证预测结果的正确性(兼顾你提到的"是否崩溃"需求)
    # assert result is not None
    # assert isinstance(result, expected_output_type)
    
    # 设置最大允许时间(比如100ms,注意单位是秒,所以写0.1)
    assert benchmark.stats["mean"] <= 0.1, f"预测耗时超过100ms,实际平均耗时{benchmark.stats['mean']*1000:.2f}ms"

第三步:运行测试

直接用pytest运行即可,pytest-benchmark会自动收集速度测试的详细统计结果:

pytest tests/test_speed.py -v

如果测试超时,会直接抛出断言错误标记测试失败;如果通过,会输出平均值、中位数、标准差等性能数据。

针对lidtk的额外提示

作为语言识别工具包,lidtk的测试需要注意:

  • 确保input_generator生成的是模型预期的输入格式(比如MFCC特征、文本向量等)
  • 如果需要验证不同输入下的速度稳定性,可以用参数化测试多跑几轮:
@pytest.mark.parametrize("test_input", [input_generator() for _ in range(5)])
def test_classifier_predict_multiple_inputs(benchmark, test_input):
    result = benchmark(classifier_predict, test_input)
    assert benchmark.stats["mean"] <= 0.1

关于tox的集成

把速度测试和其他单元测试放在一起,tox会自动运行所有测试。如果想把速度测试单独分组(比如默认不跑,仅在需要时执行),可以用pytest的标记功能:

  1. 给测试用例加标记:
@pytest.mark.speed
def test_classifier_predict_speed(benchmark):
    # ... 测试逻辑 ...
  1. 在tox.ini里配置分组规则:
[testenv]
commands = pytest tests/ -m "not speed"

[testenv:speed]
commands = pytest tests/ -m "speed"

这样默认tox只跑普通单元测试,想测速度就运行tox -e speed。


内容的提问来源于stack exchange,提问作者Martin Thoma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:15:12