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

vasudevram vasudevram at gmail.com
Thu May 24 12:39:35 EDT 2007


On May 24, 8:36 pm, "silverburgh.me... at gmail.com"
<silverburgh.me... at gmail.com> wrote:
> Hi,
>
> I am using timeit to time a global function like this
>
> t = timeit.Timer("timeTest()","from __main__ import timeTest")
> result = t.timeit();
>
> But how can i use timeit to time a function in a class?
> class FetchUrlThread(threading.Thread):
>     def aFunction(self):
>            # do something ....
>
>     def run(self):
>             # how can I time how long does aFunction() take here?
>             aFunction();
>
> Thank you.

Try this:

    def run(self):
        import time
        t1 = time.clock()
        aFunction();
        t2 = time.clock()
        print "aFunction took %d seconds" % int(t2 - t1 + 1)

(Code is not tested as I'm not at my PC right now).

The int() is to round it off to an integer, and the +1 is to give a
more accurate result - may not work in all cases, experiment, and
check for a ceil/floor type function in Python.

Vasudev Ram
Dancing Bison Enterprises
www.dancingbison.com





More information about the Python-list mailing list