python-3.x - 如何使用 timeit 对函数进行计时并保存结果

标签 python-3.x timeit

我正在尝试使用 timeit 比较我的函数的速度,但保存这些结果却无法实现。让我向您展示一个玩具示例,尝试比较不同的矩阵乘法函数:

from timeit import timeit
import numpy as np

def prod_tensorial (A,B)  : return np.tensordot(A,B,(-1,0))
def prod_punto (A,B)      : return np.dot(A,B)
def prod_sumeinsten (A,B) : return np.einsum('ij,jk->ik',A,B)

A = np.random.rand(1000,2000)
B = np.random.rand(2000,3000)

fs = ( prod_tensorial, prod_punto, prod_sumeinsten )
ts = [ ]
ps = [ ]

for f in fs:
    ts += [ timeit('ps += [f(A,B)]',number=1) ]     # error: ps & f didn't recognized
    #ts += [ timeit(lambda: f(A,B),number=1) ]      # it works but lossing results
    print( ts[-1] )

print(np.allclose(*ps))

如你所见,我无法保存结果。你知道我该怎么做吗?

最佳答案

函数timeit无法直接访问全局变量。您必须通过 globals 关键字提供全局变量的字典。由于变量 ps 在定时语句中首先读取,因此默认情况下将其视为本地变量。将其标记为全局:

# This part is only for testing
ps = []
def f(x,y): return x+y
A, B = 10, 11

timeit('global ps; ps += [f(A,B)]', number=1, globals=globals())

关于python-3.x - 如何使用 timeit 对函数进行计时并保存结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68417028/

相关文章:

python - 在 spacy 中深度复制 PhraseMatcher 对象不起作用

python - 如何在python中创建两个组元素之间的映射?

python - 将 lambda 表达式保存到文件

python - Timeit 模块 - 将对象传递给设置?

python - 将函数中的局部变量导入timeit

python - 如何在 Python 的 timeit 中使用 else

python - pip3 安装命令重复失败,无法创建文件 '/tmp/pip-install-xxxxx/package'

python - 优雅的关闭和信号处理

python - 如何在 Python 中测量耗时?

python - 我什么时候应该使用 file.read() 或 file.readlines()?