python - Python timeit 设置中的局部变量

标签 python string variables scope timeit

<分区>

在我阅读有关 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 与同一范围内的变量一起使用?

最佳答案

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

这也意味着,在您的函数中,您可以为 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())

关于python - Python timeit 设置中的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31565762/

相关文章:

python - 值错误 : Must pass 2-d input when trying to return statsmodels MNLogit confidence intervals

javascript - 如何在字符串中找到最长的单词并返回那些(不包括重复项)以及最大长度?

java - 字符串文字应该位于 LHS 上

c++ - 定义结构时是否可以强制字符串为特定大小?

python - 在 Python 中赋值变量值之前对变量执行操作

javascript - JavaScript 函数中的局部变量和全局变量

python - BeautifulSoup find_all 带参数

python - Google API Python 客户端 - AccessTokenRefreshError

php - 导航中的工作计数

python - Python pandas 读取大量.csv文件并分配不同的变量名