程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

10、 Python learning notes - thread - multi thread addition (compute intensive)

編輯:Python
# 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))

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved