timeit.timeit variable importing in python

六月ゝ 毕业季﹏ 提交于 2019-12-01 05:56:48

timeit.Timer takes a callable as well as a string to eval

Changed in version 2.6: The stmt and setup parameters can now also take objects that are callable without arguments. This will embed calls to them in a timer function that will then be executed by timeit(). Note that the timing overhead is a little larger in this case because of the extra function calls.

(also see the source, look for elif hasattr(stmt, '__call__'):).

Create a closure over the variables and pass it to timeit:

def func():
    var1 = 'aaa'
    var2 = 'aab'
    t1 = timeit.timeit(lambda: var1 == var2, number = 10**4)

or equivalently:

def func():
    var1 = 'aaa'
    var2 = 'aab'
    def closure():
        return var1 == var2
    t1 = timeit.timeit(closure, number = 10**4)

The accepted answer didn't work for me inside pdb debugger and a class method. The solution that worked is to add the variables to globals():

globals()['var1'] = var1
globals()['var2'] = var2
timeit.timeit(lambda: var1 == var2, number = 10**4)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!