Skip to content
Advertisement

How long does it take to create a thread in python

I’m trying to finish my programming course and I’m stuck on one exercise.

I have to count how much time it takes in Python to create threads and whether it depends on the number of threads created.

I wrote a simple script and I don’t know if it is good:

import threading
import time

def fun1(a,b):
    c = a + b
    print(c)
    time.sleep(100)
    


times = []

for i in range(10000):
    start = time.time()
    threading.Thread(target=fun1, args=(55,155)).start()
    end = time.time()
    times.append(end-start)

print(times)

In times[] I got a 10000 results near 0.0 or exacly 0.0.

And now I don’t know if I created the test because I don’t understand something, or maybe the result is correct and the time of creating a thread does not depend on the number of already created ones?

Can U help me with it? If it’s worng solution, explain me why, or if it’s correct confirm it? :)

Advertisement

Answer

So there are two ways to interpret your question:

  1. Whether the existence of other threads (that have not been started) affects creation time for new threads
  2. Whether other threads running in the background (threads already started) affects creation time for new threads.

Checking the first one

In this case, you simply don’t start the threads:

import threading
import time

def fun1(a,b):
    c = a + b
    print(c)
    time.sleep(100)
    


times = []

for i in range(10):
    start = time.time()
    threading.Thread(target=fun1, args=(55,155))  # don't start
    end = time.time()
    times.append(end-start)

print(times)

output for 10 runs:

[4.696846008300781e-05, 2.8848648071289062e-05, 2.6941299438476562e-05, 2.5987625122070312e-05, 2.5987625122070312e-05, 2.5987625122070312e-05, 2.5987625122070312e-05, 2.5987625122070312e-05, 2.5033950805664062e-05, 2.6941299438476562e-05]

As you can see, the times are about the same (as you would expect).

Checking the second one

In this case, we want the previously created threads to keep running as we create more threads. So we give each thread a task that never finishes:

import threading
import time

def fun1(a,b):
    while True:
      pass # never ends
    


times = []

for i in range(100):
    start = time.time()
    threading.Thread(target=fun1, args=(55,155)).start()
    end = time.time()
    times.append(end-start)

print(times)

output:

Over 100 runs, the first one took 0.0003440380096435547 whereas the last one took 0.3017098903656006 so there’s quite a magnitude of increase there.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement