[英]Importing a local variable in a function into timeit
I need to time the execution of a function across variable amounts of data. 我需要计算跨越可变数据量的函数的执行时间。
def foo(raw_data):
preprocessed_data = preprocess_data(raw_data)
time = timeit.Timer('module.expensive_func(preprocessed_data)', 'import module').timeit()
However, preprocessed_data
is not a global variable. 但是,
preprocessed_data
不是全局变量。 It cannot be imported with from __main__
. 它不能
from __main__
导入。 It is local to this subroutine. 它是本子程序的本地。
How can i import data
into the timeit.Timer
environment? 如何将
data
导入timeit.Timer
环境?
Pass it a callable to time, rather than a string. 将它传递给时间,而不是字符串。 (Unfortunately, this introduces some extra function call overhead, so it's only viable when the thing to time swamps that overhead.)
(不幸的是,这会引入一些额外的函数调用开销,因此只有当时间淹没那个开销时它才可行。)
time = timeit.timeit(lambda: module.expensive_func(data))
In Python 3.5 and up, you can also specify an explicit globals
dictionary with a string statement to time: 在Python 3.5及更高版本中,您还可以使用字符串语句指定显式
globals
字典到时间:
time = timeit.timeit('module.expensive_func(data)',
globals={'module': module, 'data': data})
The accepted answer didn't work for me inside pdb
debugger and a class method. 在
pdb
调试器和类方法中,接受的答案对我不起作用。 The solution that worked is to add the variables to globals()
: 有效的解决方案是将变量添加到
globals()
:
globals()['data'] = data
globals()['self'] = self
timeit.timeit(lambda: self.function(data))
Note that the timing overhead is a little larger in this case because of the extra function calls.
请注意,由于额外的函数调用,在这种情况下,时序开销会略大一些。 [source]
[资源]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.