0

I am trying to time a simple Python method using timeit but I keep getting the following error

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

The code, as shown below, creates a 'tree' object and then I attempt to pass that object in the Timer object. I guess this is where the problem is.

Note that if instead I pass binarytree.mkthing(0,10) to Timer the code works. However doing this calls mkthing at every pass. I want to call it only once and then reuse it.

How should I go about doing that?

if __name__=="__main__":

    tree = mkthing(0,10)

    t1=timeit.Timer("binarytree.traverse_asc(locals()['tree'],binarytree.printout)","import binarytree")
    print t1.repeat(2, 3)
jule64
  • 487
  • 1
  • 6
  • 19

2 Answers2

1

you could do: from __main__ import tree in the setup code:

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

Or better yet, move the making of the thing (tree) into the setup code all-together:

t1 = timeit.Timer("binarytree.traverse_asc(tree,binarytree.printout)",
                  setup = "import binarytree; tree = mkthing(0,10)")
mgilson
  • 300,191
  • 65
  • 633
  • 696
0

timeit.Timer evals the statement you pass it in inside the timeit module. It can't access the tree variable.

The question is somewhat related and should help you get the gist.

Community
  • 1
  • 1
emperorcezar
  • 334
  • 1
  • 9