I want to time some code that depends on some setup. The setup code looks a little like this:
>>> b = range(1, 1001)
And the code I want to time looks vaguely like this:
>>> sorted(b)
Except my code uses a different function than sorted. But that ain't important right now.
Anyhow, I know how to time this code as long as I pass in strings to timeit:
>>> import timeit
>>> t = timeit.Timer("sorted(b)", "b = range(1, 1001)")
>>> min(t.repeat(3, 100))
How do I use a setup callable and have it put stuff into the namespace that the stmt callable can access?
In other words, how do I do the same thing as the code above, but with callables, and not strings containing callables?
Incidentally, the bigger goal here is to reuse code from my unit tests to measure performance:
import unittest
class TestSorting(unittest.TestCase):
def setUp(self):
self.b = range(1, 1001)
def test_sorted(self):
sorted(self.b)
I expect to do a little work. The timeit setup will need to make an instance of TestSorting and somehow the stmt code will have to use that particular instance.
Once I understand how to have the timeit setup put stuff into the same namespace as the timeit stmt, I'll look into how to translate unittest.TestCase instances into something that can feed right into timeit.Timer.
Matt