Ad

How To Measure Time Taken Of Multi-threads Created In A Loop?

- 1 answer

I want to measure how much time it takes to finish running the code with multiple threads in python.

If I put join inside the loop, it will stop the loop (main thread) from keep creating new threads. It will run the sleep() one by one.

If I put join on the thread which I use to create thread_testing, the join won't work somehow. It prints out the time immediately.

def sleep(name):
    print("{} going to sleep".format(name))
    time.sleep(5)
    print("{} wakes up after 5 seconds".format(name))


def thread_testing():
    for i in range(3):
        t = threading.Thread(target=sleep, name='thread' + str(i), args=(i,)
        t.start()
        # t.join() #1

if __name__ == '__main__':
    start = time.time()
    t = threading.Thread(target=thread_testing, name='threadx')
    t.start()
    t.join() #2
    print(time.time() - start)

Desired output:

1 sleep
2 sleep
3 sleep
1 wake up after 5
2 wake up after 5
3 wake up after 5 
5.xxx secs
Ad

Answer

Join will wait for your thread. That is why your threads were executed one by one. What you have to do is:

  • Start all threads
  • Store them somewhere
  • Once everything is started wait for every thread to finish.

Assuming you don't need the first thread started in main:

import time
import threading

def sleep(name):
    print("{} going to sleep".format(name))
    time.sleep(5)
    print("{} wakes up after 5 seconds".format(name))


def thread_testing():
    threads = []
    for i in range(3):
        t = threading.Thread(target=sleep, name='thread' + str(i), args=(i,))
        t.start()
        threads.append(t)
    for t in threads:
        t.join()

if __name__ == '__main__':
    start = time.time()
    thread_testing()
    print(time.time() - start)
Ad
source: stackoverflow.com
Ad