-1

Say I want to test two heap implementations like this:

def test_heap():
    for i in range(15):
        test_list = random.sample(range(10000), 1000)
        print(timeit("h = heap1(test_list)", "setup"))
        print(timeit("h = heap2(test_list)", "setup"))

if __name__ == "__main__":
    test_heap()

I don't want to put whatever is in test_heap into the main, what should the setup statement be so I can import test_list into timeit?

Liumx31
  • 1,190
  • 1
  • 16
  • 33

1 Answers1

1

Some of the names you need are apparently globals. (At least, I assume that they are because they aren't shown.) You can just import those from __main__.

 "from __main__ import heap1, heap2"

test_list is tougher. You can get it from your function's locals(), but that's not available inside timeit(). Probably easiest thing to do in this case, since it's just a list of integers, is to construct a string version of the list and have Python evaluate it.

"test_list = %r" % test_list

(This wouldn't work so well if you had e.g. object instances.)

Put them together with a semicolon and you get the following setup string:

 "from __main__ import heap1, heap2; test_list = %r" % test_list

(also, remember to close your parentheses)

kindall
  • 178,883
  • 35
  • 278
  • 309