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)

2 Answers 2

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)")
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.