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

如何测量Python机器学习模型的预测速度(单位:秒)?

测量机器学习模型预测速度的方法

方法一:使用time.perf_counter(单次计时,精确测量短间隔)

这是Python中测量短时间执行速度最精确的方式,适合直接测量单次预测的耗时:

import time
from sklearn.tree import DecisionTreeClassifier

# 创建并训练决策树模型
clf = DecisionTreeClassifier(criterion="entropy", max_depth=3)
clf = clf.fit(X_train, y_train)

# 对预测步骤计时
start = time.perf_counter()
y_pred = clf.predict(X_test)
end = time.perf_counter()

print(f"预测执行耗时: {end - start:.6f} 秒")

方法二:使用timeit(多次运行取平均,降低误差)

如果测试数据集很小,单次预测耗时极短,推荐用timeit多次运行后取平均,避免单次波动带来的误差:

from timeit import timeit
from sklearn.tree import DecisionTreeClassifier

# 创建并训练模型
clf = DecisionTreeClassifier(criterion="entropy", max_depth=3)
clf = clf.fit(X_train, y_train)

# 封装预测逻辑为函数
def run_prediction():
    return clf.predict(X_test)

# 运行100次,计算单次平均耗时
avg_time = timeit(run_prediction, number=100) / 100
print(f"单次预测平均耗时: {avg_time:.6f} 秒")

注意事项

  • 若X_test数据量较大,单次计时的结果已经足够可靠;
  • 多次运行取平均时,可以根据实际情况调整number参数(比如数据量小就调大,数据量大就调小)。

内容的提问来源于stack exchange,提问作者Ruben van Oranje

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 06:06:23