Python:有没有一种方法可以使用timeit.timeit()导入变量? [英] Python: is there a way to import a variable using timeit.timeit()?
问题描述
假设我有一些函数需要一个数组并将每个元素更改为0.
Suppose I have some function that takes an array and changes every element to be 0.
def function(array):
for i in range(0,len(array)):
array[i] = 0
return array
我想测试此函数在随机数组上运行需要多长时间,我希望在timeit测试中生成OUTSIDE.换句话说,我不想将生成数组所需的时间包括在时间中.
I want to test how long this function takes to run on a random array, which I wish to generate OUTSIDE of the timeit test. In other words, I don't want to include the time it takes to generate the array into the time.
我首先将随机数组存储在变量x中并执行以下操作:
I first store a random array in a variable x and do:
timeit.timeit("function(x)",setup="from __main__ import function")
但这给了我一个错误:NameError:未定义全局名称'x'
But this gives me an error: NameError: global name 'x' is not defined
我该怎么做?
推荐答案
还要从__main__
导入:
Import x
from __main__
as well:
timeit.timeit("function(x)", setup="from __main__ import function, x")
就像function
一样,x
是__main__
模块中的名称,可以导入到timeit
设置中.
Just like function
, x
is a name in the __main__
module, and can be imported into the timeit
setup.
这篇关于Python:有没有一种方法可以使用timeit.timeit()导入变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!