我有几个函数需要用来评估使用 timeit 模块的性能。
对于初学者,我尝试使用 Timer 对象来评估在随机整数列表上运行的顺序搜索函数,该函数应返回以秒为单位的执行时间。该函数返回 -1 的 False 值(因为它永远找不到 -1),但同时给出以下错误。这是完整的输出:
False
Traceback (most recent call last):
File "D:/.../search-test.py", line 37, in <module>
main()
File "D:/.../search-test.py", line 33, in main
print(t1.timeit(number=100))
File "C:\...\Anaconda2\lib\timeit.py", line 202, in timeit
timing = self.inner(it, self.timer)
File "<timeit-src>", line 6, in inner
TypeError: sequential_search() takes exactly 2 arguments (0 given)
这是我的程序:
from timeit import Timer
import random
def sequential_search(a_list, item):
pos = 0
found = False
while pos < len(a_list) and not found:
if a_list[pos] == item:
found = True
else:
pos = pos+1
return found
def num_gen(value):
myrandom = random.sample(xrange(0, value), value)
return myrandom
def main():
new_list = num_gen(100)
print(sequential_search(new_list, -1))
t1 = (Timer("sequential_search()", "from __main__ import sequential_search"))
print(t1.timeit(number=100))
if __name__ == '__main__':
main()
我是一个编程新手,可以诚实地说我正在挣扎。这个错误对我来说没有任何意义。我不明白为什么当它们已经在 main() 中传递时它还要求顺序搜索函数参数。将参数插入 Timer 语句并不能解决问题。
请帮我理解我搞砸了什么。谢谢!
最佳答案
这就是制作计时器对象的方法 -
t1 = (Timer("sequential_search(new_list, -1)", setup="from __main__ import sequential_search, num_gen;new_list=num_gen(100);"))
print(t1.timeit(number=100))
输出 -
False
0.0014021396637
它不起作用只是因为你没有传递参数。因此,只需在 setup
中初始化变量(但不一定),就可以开始了。
关于python - 在 Python 中使用 Timer 对象的错误输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42490901/