【问题标题】:How to time functions with timeit and save results如何使用 timeit 对函数计时并保存结果
【发布时间】:2021-07-17 02:50:47
【问题描述】:

我正在尝试使用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))

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

【问题讨论】:

    标签: python-3.x timeit


    【解决方案1】:

    函数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())
    

    【讨论】:

    • 我仍然遇到同样的错误。你能检查一下吗? colab.research.google.com/drive/…
    • 非常感谢@DYZ!为了解决所有问题,我为我的示例添加了完整的行:ts += [ timeit('global ps,f; ps += [f(A,B)]', number=1, globals=globals()) ]
    • f 已经是全局的了,不需要标记。但无论如何。
    • 你是对的,将 ds 声明为全局就足够了。再次感谢! ts += [ timeit('global ps; ps += [f(A,B)]', number=1, globals=globals()) ]
    • 我刚刚读到了这一点。这是因为ps 在脚本中被赋值,就像一个函数一样。否则,添加globals=globals() 参数就足够了。
    猜你喜欢
    • 2013-10-01
    • 2012-06-15
    • 1970-01-01
    • 2015-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多