Python timeit设置中的局部变量

2024-04-26 22:22:22 发布

您现在位置:Python中文网/ 问答频道 /正文

在我读到的所有关于timeit的地方,我发现只有这样才能使用变量:

s1 = 'abc'
s2 = 'abc'
timeit.timeit('s1==s2', 'from __main__ import s1, s2', number=10**4)

或者

s1 = 'abc'
s2 = 'abc'
def func():
    timeit.time('s1==s2', 'from __main__ import s1,s2', number=10**4)

这意味着只要变量在主程序中,也可以在函数中使用timeit.timeit。 我想将timeit.timeit与它所在范围内的变量一起使用,例如:

def func():
    s1 = 'abc'
    s2 = 'abc'
    timeit.timeit(...)

如你所见,我的问题是:

当变量都不在主程序中时,如何将timeit.timeit与同一范围内的变量一起使用?


Tags: 函数fromimportnumbertimemaindef地方
2条回答

I would like to use timeit.timeit with variables that are within the scope it is in.

TLDR:

使用一个lambda闭包(之所以这样叫是因为它在函数中的变量上关闭):

def func():
    s1 = 'abc'
    s2 = 'abc'
    return timeit.timeit(lambda: s1 == s2)

我想这正是你想要的。

>>> func()
0.12512516975402832

说明

所以在全局范围内,你想使用全局范围,和局部范围,局部范围?在全局作用域上,locals()返回与globals()相同的结果,因此您可以', '.join(locals())并将其粘贴到'from __main__ import '的末尾,或者globals()因为它们在全局作用域上是等价的:

>>> s1 = 'abc'
>>> s2 = 'abc'
>>> timeit.timeit('s1==s2', 'from __main__ import ' + ', '.join(globals()))
0.14271061390928885

您可以使用函数和globals()来完成此操作,但不能使用locals():

s1 = 'abc'
s2 = 'abc'
def func():
    return timeit.timeit('s1==s2', 'from __main__ import ' + ', '.join(globals()))

以及

>>> func()
0.14236921612231157

但是下面的方法不起作用,因为您必须从import语句访问隐藏在函数的本地范围中的变量:

def func():
    s1 = 'abc'
    s2 = 'abc'
    return timeit.timeit('s1==s2', 'from __main__ import ' + ', '.join(locals()))

但是,因为您可以简单地将函数传递给timeit,所以可以做的是:

def func(s1='abc', s2='abc'):
    s1 == s2

以及

>>> timeit.timeit(func)
0.14399981498718262

这也意味着,在func中,可以为timeit提供lambda闭包:

def func():
    s1 = 'abc'
    s2 = 'abc'
    return timeit.timeit(lambda: s1 == s2)

或全功能定义:

def func():
    s1 = 'abc'
    s2 = 'abc'
    def closure():
        return s1 == s2
    return timeit.timeit(closure)

我想这正是你想要的。

>>> func()
0.12512516975402832

When they're both not in the main program

如果要从__main__以外的其他模块加入全局变量,请使用以下命令:

'from ' + __name__ + ' import ' + ', '.join(globals())

正如jornsharpe所解释的,在timeit作用域上运行的函数没有(直接的)访问something outside its scope that is not a global的方法。

您应该考虑重写您的函数,将它需要用作参数的变量作为参数-使用globals通常被认为是一种错误的做法,会导致很多问题。

为了向timeit.timeit提供参数,可以使用partial function

from functools import partial

def func(s1,s2):
    pass

timeit.timeit( partial( func, s1='bla', s2='bla' ) )

相关问题 更多 >