I am multithreading a operation in python to make it faster but it is still not faster

Category: python multithreading (4 Views)

This is the program below but I am confused the multithreaded program runs slower when compared to the program which is not multithreaded. What could be the reason. Why multithreading is slower than single thread (main thread) computation??

import numpy as np
from threading import *
from functools import reduce
import time

#Multithreading
l = list(range(1,10001))
b = []
b1 = []
c = []
c1 = []
a = []
d = []
d1 = []
start_time = time.time()
print("######### with multithreading##########")
class ta1(Thread):
    def run(self):
        global b
        b = l[0:2500]
        b = list(map(lambda x: x*x ,b))
class ta2(Thread):
    def run(self):
        global b1
        b1 = l[2500:5000]
        b1 = list(map(lambda x: x*x ,b1))
class ta3(Thread):
    def run(self):
        global d
        d = l[5000:7500]
        d = list(map(lambda x: x*x ,b1))
class ta4(Thread):
    def run(self):
        global d1
        d1 = l[7500:10001]
        d1 = list(map(lambda x: x*x ,b1))
t1 = ta1()
t2 = ta2()
t3 = ta3()
t4 = ta4()
t1.start()
t2.start()
t3.start()
t4.start()
a = [*b,*b1,*d,*d1]
print(a)
end_time = time.time()
print(end_time-start_time)

print('########### normal without threading ############')
xc = time.time()
c = list(map(lambda x:x*x,l))
print(c)
xc1 = time.time()
print(xc1-xc)

And the output time for both was

######### with  multithreading##########

0.7726929187774658
########### normal without threading ############

0.5661568641662598
🔴 No definitive solution yet

📌 Solution 1

As @larsks stated, Python does not support running multiple threads in parallel. This makes it slower to use threading, as setting up the threads slows down the program.