單線程和多線程耗時對比:(請自行對比,深刻理解)
單線程運行:
"""
@author: zhangjun.xue
@time: 2020/3/30 14:20
@file: threading_queue.py.py
@desc: 多線程去消費一個隊列的例子
"""
import threading
import time
import queue
# 下面來通過多線程來處理Queue裏面的任務:
def work(q):
while True:
if q.empty():
return
else:
t = q.get()
print("當前線程sleep {} 秒".format(t))
time.sleep(t)
def main():
q = queue.Queue()
for i in range(5):
q.put(i) # 往隊列裏生成消息
# 單線程
work(q)
# 多線程
# thread_num = 5
# threads = []
# for i in range(thread_num):
# t = threading.Thread(target=work, args=(q,))
# # args需要輸出的是一個元組,如果只有一個參數,後面加,表示元組,否則會報錯
# threads.append(t)
#
# for i in range(thread_num):
# threads[i].start()
# for i in range(thread_num):
# threads[i].join()
if __name__ == "__main__":
start = time.time()
main()
print('耗時:', time.time() - start)
輸出:
當前線程sleep 0 秒
當前線程sleep 1 秒
當前線程sleep 2 秒
當前線程sleep 3 秒
當前線程sleep 4 秒
耗時: 10.000863552093506
兩個線程去消費長度爲5的隊列:
"""
@author: zhangjun.xue
@time: 2020/3/30 14:20
@file: threading_queue.py.py
@desc: 多線程去消費一個隊列的例子
"""
import threading
import time
import queue
# 下面來通過多線程來處理Queue裏面的任務:
def work(q):
while True:
if q.empty():
return
else:
t = q.get()
print("當前線程sleep {} 秒".format(t))
time.sleep(t)
def main():
q = queue.Queue()
for i in range(5):
q.put(i) # 往隊列裏生成消息
# 單線程
# work(q)
# 多線程
thread_num = 2
threads = []
for i in range(thread_num):
t = threading.Thread(target=work, args=(q,))
# args需要輸出的是一個元組,如果只有一個參數,後面加,表示元組,否則會報錯
threads.append(t)
for i in range(thread_num):
threads[i].start()
for i in range(thread_num):
threads[i].join()
if __name__ == "__main__":
start = time.time()
main()
print('耗時:', time.time() - start)
輸出:
當前線程sleep 0 秒
當前線程sleep 1 秒
當前線程sleep 2 秒
當前線程sleep 3 秒
當前線程sleep 4 秒
耗時: 6.0027899742126465
5個線程去消費一個長度爲5的隊列:
"""
@author: zhangjun.xue
@time: 2020/3/30 14:20
@file: threading_queue.py.py
@desc: 多線程去消費一個隊列的例子
"""
import threading
import time
import queue
# 下面來通過多線程來處理Queue裏面的任務:
def work(q):
while True:
if q.empty():
return
else:
t = q.get()
print("當前線程sleep {} 秒".format(t))
time.sleep(t)
def main():
q = queue.Queue()
for i in range(5):
q.put(i) # 往隊列裏生成消息
# 單線程
# work(q)
# 多線程
thread_num = 5
threads = []
for i in range(thread_num):
t = threading.Thread(target=work, args=(q,))
# args需要輸出的是一個元組,如果只有一個參數,後面加,表示元組,否則會報錯
threads.append(t)
for i in range(thread_num):
threads[i].start()
for i in range(thread_num):
threads[i].join()
if __name__ == "__main__":
start = time.time()
main()
print('耗時:', time.time() - start)
輸出:
當前線程sleep 0 秒
當前線程sleep 1 秒
當前線程sleep 2 秒
當前線程sleep 3 秒
當前線程sleep 4 秒
耗時: 4.0016114711761475