Need help using callables and setup in timeit.Timer

M

Matthew Wilson

I want to time some code that depends on some setup. The setup code
looks a little like this:

And the code I want to time looks vaguely like this:

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:

How do I use a setup callable and have it put stuff into the namespace
that the stmt callable can access?

In other words, I want to do the same thing as above, but using
callables as the parameters to timeit.Timer, not strings of python code.

Here's my long-run goal. I want to reuse code from my unit tests to
test 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 have 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 attack how to translate
unittest.TestCase instances into something that can feed right into
timeit.Timer.

Matt
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top