How can I time how much each thread takes?

7stud bbxx789_05ss at yahoo.com
Wed Apr 4 03:36:32 EDT 2007


On Apr 3, 11:00 pm, "silverburgh.me... at gmail.com"
<silverburgh.me... at gmail.com> wrote:
> Hi,
>
> I have the following code which spawn a number of thread and do
> something (in the run method of MyThread).
> how can I record how much time does EACH thread takes to complete the
> 'run'?
>
>   for j in range(threadCount):
>                 t = MyThread(testNo)
>                 threads.append(t)
>                 t.start()
>                 testNo += 1
>
>   for t in threads:
>                 print "len = %d", len(threads)
>                 t.join()
>
> I have read example of timeit.Timer() funcion, but I don' t know how
> can i use it in a multiple thread program?
> Thank you for any help.

How about this:

import time, threading

class MyThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.begin = 0
        self.end = 0

    def run(self):
        print "thread starting in background"
        self.begin = time.time()
        time.sleep(3)
        self.end = time.time()
        print "thread ending"

mt = MyThread()
mt.start()
print "main still running in foreground"

print "main going to wait for thread to end ....."
mt.join()

diff = mt.end - mt.begin
print "Thread's run() time was: %.5f" % diff




More information about the Python-list mailing list