I tried implementing multi-threading to do below square()
operation on a number.
But it is taking too much time when compared to scenario where multi-threading is not used.
Please check the code below and the corresponding time taken to execute
import datetime
import time
from concurrent.futures import ThreadPoolExecutor
import multiprocessing
def square(x):
#time.sleep(2)
print("The result is:: %s\n" % str(x*x))
nums = [1,2,3,4,5]
dict = {}
dict[1] = 10
dict[2] = 20
dict[3] = 30
start = datetime.datetime.now()
# time taken = 41 ms
for index, value in dict.items():
square(value)
# time taken= 1730 ms
with ThreadPoolExecutor(max_workers=5) as executor:
for index,value in dict.items():
executor.submit(square, value)
# time taken = 1034 ms
with ThreadPoolExecutor(max_workers=5) as executor:
executor.map(square, dict)
# time taken : 35860 ms
a_pool = multiprocessing.Pool()
a_pool.map(square, dict)
end = datetime.datetime.now()
print("Total time::", end - start)
A few questions:
- Why multi-threading is taking more time than normal process without threads?
- I read that multi-processing is faster than multi-threading. But in above example, it is taking more time than multi-threaded environment.
- Any suggestions to implement which can enhance the performance and can cause concurrent executions?
Note: The above is just a pseudo code. I wanted to implement multi-threading in my actual project but there also, it is showing the same behavior.