pys*_*ent 5 python string variables scope timeit
在我读到的关于timeit的所有地方,我发现只能以这种方式使用变量:
s1 = 'abc'
s2 = 'abc'
timeit.timeit('s1==s2', 'from __main__ import s1, s2', number=10**4)
Run Code Online (Sandbox Code Playgroud)
要么
s1 = 'abc'
s2 = 'abc'
def func():
timeit.time('s1==s2', 'from __main__ import s1,s2', number=10**4)
Run Code Online (Sandbox Code Playgroud)
which means that you can also use timeit.timeit in a function as long as the variables are in the main program. I would like to use timeit.timeit with variables that are within the scope it is in, for example:
def func():
s1 = 'abc'
s2 = 'abc'
timeit.timeit(...)
Run Code Online (Sandbox Code Playgroud)
As you can see my question is:
How can I use timeit.timeit with the variables that are in the same scope, when they're both not in the main program?
Aar*_*all 10
我想将timeit.timeit与其所在范围内的变量一起使用.
TLDR:
使用lambda闭包(所谓的因为它关闭了函数中的变量):
def func():
s1 = 'abc'
s2 = 'abc'
return timeit.timeit(lambda: s1 == s2)
Run Code Online (Sandbox Code Playgroud)
而且我认为这只是你所要求的.
>>> func()
0.12512516975402832
Run Code Online (Sandbox Code Playgroud)
说明
那么在全局范围内,您想要使用全局变量,局部范围,本地变量?在全局范围内,locals()返回相同的结果globals(),因此您可以', '.join(locals())坚持到最后'from __main__ import ',或者globals()它们在全局范围内是等效的:
>>> s1 = 'abc'
>>> s2 = 'abc'
>>> timeit.timeit('s1==s2', 'from __main__ import ' + ', '.join(globals()))
0.14271061390928885
Run Code Online (Sandbox Code Playgroud)
您可以使用函数执行此操作globals(),但也不能使用locals():
s1 = 'abc'
s2 = 'abc'
def func():
return timeit.timeit('s1==s2', 'from __main__ import ' + ', '.join(globals()))
Run Code Online (Sandbox Code Playgroud)
和
>>> func()
0.14236921612231157
Run Code Online (Sandbox Code Playgroud)
但是下面的方法不起作用,因为你必须从import语句中访问隐藏在函数本地范围内的变量:
def func():
s1 = 'abc'
s2 = 'abc'
return timeit.timeit('s1==s2', 'from __main__ import ' + ', '.join(locals()))
Run Code Online (Sandbox Code Playgroud)
但是因为你可以简单地将函数传递给timeit,你可以做的是:
def func(s1='abc', s2='abc'):
s1 == s2
Run Code Online (Sandbox Code Playgroud)
和
>>> timeit.timeit(func)
0.14399981498718262
Run Code Online (Sandbox Code Playgroud)
所以这也意味着,在你的函数中,你可以提供一个lambda闭包时间:
def func():
s1 = 'abc'
s2 = 'abc'
return timeit.timeit(lambda: s1 == s2)
Run Code Online (Sandbox Code Playgroud)
或者全功能def:
def func():
s1 = 'abc'
s2 = 'abc'
def closure():
return s1 == s2
return timeit.timeit(closure)
Run Code Online (Sandbox Code Playgroud)
而且我认为这只是你所要求的.
>>> func()
0.12512516975402832
Run Code Online (Sandbox Code Playgroud)
当他们都不在主程序中时
如果你想用一个设置加入全局变量,而不是从其他模块加入__main__,请使用:
'from ' + __name__ + ' import ' + ', '.join(globals())
Run Code Online (Sandbox Code Playgroud)