# Use multithreading to run continuous addition , Compare the continuous addition time of a single thread , It is proved that multithreading is not very effective for computing intensive (python There is no real multithreading )
"""
1、 because python Of GIL Mechanism , Lead to python There is no real multithreading , So for compute intensive models , Multithreading may even be less efficient than single threading ( Because there will be thread switching )
2、python2 Multithreading is indeed slower than a single thread ,python3 After optimization, multi thread is slightly higher than single thread
"""
import threading
import time
def add(n):
num = 0
for i in range(n):
num += 1
print(num)
if __name__ == '__main__':
# Execute non multiline first
start1_time = time.time()
add(20000000)
add(50000000)
end1_time = time.time()-start1_time
print(' Single thread takes time {}'.format(end1_time))
# Execute multiline
t1 = threading.Thread(target=add, args=(20000000,))
t2 = threading.Thread(target=add, args=(50000000,))
start2_time = time.time()
t1.start()
t2.start()
t1.join()
t2.join()
end2_time = time.time() - start2_time
print(' Multithreading takes time {}'.format(end2_time))