Need help using callables and setup in timeit.Timer

Discussion in 'Python' started by Matthew Wilson, May 12, 2010.

  1. 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, 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
     
    Matthew Wilson, May 12, 2010
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Dan Christensen
    Replies:
    4
    Views:
    576
    Peter Otten
    Jul 14, 2004
  2. Replies:
    2
    Views:
    271
  3. =?iso-8859-1?B?R3V5b24gTW9y6WU=?=

    Question about re.sub and callables

    =?iso-8859-1?B?R3V5b24gTW9y6WU=?=, Dec 30, 2005, in forum: Python
    Replies:
    3
    Views:
    317
    Fredrik Lundh
    Dec 30, 2005
  4. Dongsheng Ruan
    Replies:
    1
    Views:
    432
    Gabriel Genellina
    Jan 19, 2007
  5. ssecorp
    Replies:
    5
    Views:
    314
    Steven D'Aprano
    Aug 4, 2008
Loading...

Share This Page