Threading
import time
import threading
Without Multithreading
def calc_square(arr):
print("calculate square numbers")
for n in arr:
time.sleep(1)
print('square:',n*n)
def calc_cube(arr):
print("calculate cube of numbers")
for n in arr:
time.sleep(1)
print('cube:',n*n*n)
arr = [2,3,8,9]
t = time.time()
calc_square(arr)
calc_cube(arr)
print("done in : ",time.time()-t)
Output:-
calculate square numbers
square: 4
square: 9
square: 64
square: 81
calculate cube of numbers
cube: 8
cube: 27
cube: 512
cube: 729
done in : 8.093624591827393
With Multithreading
def calc_square(arr):
print("calculate square numbers")
for n in arr:
time.sleep(1)
print('square:',n*n)
def calc_cube(arr):
print("calculate cube of numbers")
for n in arr:
time.sleep(1)
print('cube:',n*n*n)
arr = [2,3,8,9]
t = time.time()
t1= threading.Thread(target=calc_square, args=(arr,))
t2= threading.Thread(target=calc_cube, args=(arr,))
t1.start()
t2.start()
t1.join()
t2.join()
print("done in : ",time.time()-t)
calculate square numberscalculate cube of numbers
square:cube: 8
4
square:cube: 9
27
cube: 512
square: 64
square:cube: 81
729
done in : 4.0517966747283936
Last updated