python中,time.sleep()屬於計算密集型任務
使用多進程可明顯提升效率
多線程適用於IO密集型任務,對於科學計算類任務,多線程非但不能提升效率,還有可能因爲線程間切換調度而增加時間的消耗
import multiprocessing
import time
from queue import Queue
from threading import Thread
qurl = Queue()
def func(msg):
print("msg:", msg)
time.sleep(3)
print("end")
def make_data():
for i in range(10):
qurl.put(i)
print('------ qurl.qsize() = ', qurl.qsize())
def custom_process():
pool = multiprocessing.Pool(processes=10)
while not qurl.empty():
data = qurl.get()
print('--- data = ', data)
pool.apply_async(func, (data,)) # 維持執行的進程總數爲processes,當一個進程執行完畢後會添加新的進程進去
pool.close()
pool.join() # 調用join之前,先調用close函數,否則會出錯。執行完close後不會有新的進程加入到pool,join函數等待所有子進程結束
def custom_thread():
while not qurl.empty():
data = qurl.get()
print('--- data = ', data)
multi_thread_work(func, data)
# 多線程
def multi_thread_work(func, data):
ths = []
for i in range(10):
th = Thread(target=func, args=(data, ))
th.start()
ths.append(th)
for th in ths:
th.join()
if __name__ == "__main__":
start_time = time.time()
make_data()
print('make_data_end')
# custom_process() # 3秒結束戰鬥 time.sleep()屬於計算密集型任務,使用多進程可明顯提升效率
custom_thread() # 30秒才結束戰鬥,多線程適用於IO密集型任務,對於科學計算類任務,多線程非但不能提升效率,還有可能因爲線程間切換調度而增加時間的消耗
print('all task consum time = ', time.time() - start_time)