How can I time a method of a class in python using Timeit

7stud bbxx789_05ss at yahoo.com
Thu May 24 16:38:16 EDT 2007


On May 24, 12:23 pm, "silverburgh.me... at gmail.com"
<silverburgh.me... at gmail.com> wrote:
> On May 24, 12:41 pm, 7stud <bbxx789_0... at yahoo.com> wrote:
>
>
>
> > Actually, you can do this:
>
> > class Dog(object):
> >     def aFunction(self):
> >         result = 20 + 2
> >     def run(self):
> >         #do stuff
> >         aFunction()
> >         #do other stuff
> > import timeit
>
> > t = timeit.Timer("d.aFunction()", "from __main__ import Dog; d =
> > Dog()")
> > print t.timeit()
>
> > Since you only want to time aFunction(), you can call it directly.
>
> Can 't = timeit.Timer()' run inside a thread?
> And I have multiple threads running this 't = timeit.Time()' function?

Are you seeing an error like this:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.4//lib/
python2.4/threading.py", line 442, in __bootstrap
    self.run()
  File "test1.py", line 34, in run
    print t.timeit()
  File "/Library/Frameworks/Python.framework/Versions/2.4//lib/
python2.4/timeit.py", line 161, in timeit
    timing = self.inner(it, self.timer)
  File "<timeit-src>", line 3, in inner
TypeError: __init__() takes exactly 2 arguments (1 given)


That was produced by this code:

----------
import time
import timeit
import threading


t = timeit.Timer("inst.f()", "from __main__ import Dog; inst=Dog()")
print t

class Dog(threading.Thread):

    def __init__(self, id):
        self.id = id
        threading.Thread.__init__(self)

    def f(self):
        result = 20 + 3

    def run(self):
        print t
        print t.timeit()


d = Dog("d")
d.start()
--------------

I can't explain that error.   This works:

--------------
import time
import timeit
import threading


t = timeit.Timer("inst.f()", "from __main__ import Dog; inst=Dog()")

class Dog(threading.Thread):

    def f(self):
        result = 20 + 3

    def run(self):
        print t.timeit()

d = Dog()
d.start()
-----------




More information about the Python-list mailing list