【问题标题】:timeit throwing keyerror in Pythontimeit 在 Python 中抛出 keyerror
【发布时间】:2013-01-18 02:53:59
【问题描述】:

我正在尝试使用 timeit 为一个简单的 Python 方法计时,但我不断收到以下错误

File "<timeit-src>", line 6, in inner
KeyError: 'tree'

如下所示的代码创建了一个“树”对象,然后我尝试将该对象传递给 Timer 对象。我想这就是问题所在。

请注意,如果我将 binarytree.mkthing(0,10) 传递给 Timer,则代码有效。然而,这样做每次都会调用 mkthing。我只想调用一次,然后重复使用。

我该怎么做呢?

if __name__=="__main__":

    tree = mkthing(0,10)

    t1=timeit.Timer("binarytree.traverse_asc(locals()['tree'],binarytree.printout)","import binarytree")
    print t1.repeat(2, 3)

【问题讨论】:

    标签: python timeit


    【解决方案1】:

    你可以这样做:from __main__ import tree 在设置代码中:

    t1 = timeit.Timer("binarytree.traverse_asc(tree,binarytree.printout)",
                      setup = "import binarytree; from __main__ import tree")
    

    或者更好的是,将事物 (tree) 的制作全部移到设置代码中:

    t1 = timeit.Timer("binarytree.traverse_asc(tree,binarytree.printout)",
                      setup = "import binarytree; tree = mkthing(0,10)")
    

    【讨论】:

      【解决方案2】:

      timeit.Timer 评估您在 timeit 模块中传入的语句。它无法访问树变量。

      question 有点相关,应该可以帮助您了解要点。

      【讨论】:

        猜你喜欢
        • 2012-03-26
        • 1970-01-01
        • 2021-03-17
        • 2013-02-13
        • 2021-03-03
        • 2022-01-15
        • 2018-08-13
        相关资源
        最近更新 更多