0

This code takes me ~11 seconds:

def task(numbers):
    print(f"Starting")
    for number in numbers:
        number**number
task(range(10000))
task(range(10000))

And this take me the same:

def task(numbers):
    for number in numbers:
        number**number

start = time()

t1 = threading.Thread(target=task, args=(range(10000),))

t2 = threading.Thread(target=task, args=(range(10000),))

t1.start()
t2.start()


t1.join()
t2.join()

end = time()
print(end - start)

Why this code is not taking half-time if I am using 2 threads?

  • 1
    Does this answer your question? [python multi-threading slower than serial?](https://stackoverflow.com/questions/10789042/python-multi-threading-slower-than-serial) – Yevhen Kuzmovych Nov 04 '21 at 11:41
  • 2
    Also check this: https://stackoverflow.com/q/18114285/4046632 – buran Nov 04 '21 at 11:43
  • 1
    Your `task` is cpu-heavy, not i/o-heavy, so threading isn't speeding anything up. Use multiprocessing instead. – Timus Nov 04 '21 at 16:21

1 Answers1

0

Threads are good for parallelizing in/out operation, eg. when you are waiting for a response from a socket, then you can do some useful stuff in other threads and thus reduce execution time. But if you have really exhausting operation, which consumes the whole CPU, then the threading will be even slower, because you have some overhead switching between threads.

Here is a slightly modified example, but instead of expensive operation x**x, there is only sleep and the result is as expected.

from threading import Thread
from time import time, sleep

LOOPS = 10
TASKS = 5
SLEEP = 0.1

def task():
    for _ in range(LOOPS):
        sleep(SLEEP)

def timing(func):
    def wrapper():
        start = time()
        func()
        duration = time() - start
        print(duration)
    return wrapper

@timing
def serial():
    print("serial execution")
    for _ in range(TASKS):
        task()

@timing
def paralel():
    print("paralel execution")

    threads = []
    for _ in range(TASKS):
        t = Thread(target=task)
        threads.append(t)
        t.start()

    for t in threads:
        t.join()

def main():
    serial()
    paralel()

if __name__ == "__main__":
    main()
serial execution
5.0098230838775635
paralel execution
1.0120694637298584
Jan Krejci
  • 85
  • 8