您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關Python中多線程與多進程對比的示例分析,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
多線程適合于多io操作
多進程適合于耗cpu(計算)的操作
# 多進程編程 # 耗cpu的操作,用多進程編程, 對于io操作來說,使用多線程編程 import time from concurrent.futures import ThreadPoolExecutor, as_completed from concurrent.futures import ProcessPoolExecutor def fib(n): if n <= 2: return 1 return fib(n - 2) + fib(n - 1) if __name__ == '__main__': # 1. 對于耗cpu操作,多進程優于多線程 # with ThreadPoolExecutor(3) as executor: # all_task = [executor.submit(fib, num) for num in range(25, 35)] # start_time = time.time() # for future in as_completed(all_task): # data = future.result() # print(data) # print("last time :{}".format(time.time() - start_time)) # 3.905290126800537 # 多進程 ,在window環境 下必須放在main方法中執行,否則拋異常 with ProcessPoolExecutor(3) as executor: all_task = [executor.submit(fib, num) for num in range(25, 35)] start_time = time.time() for future in as_completed(all_task): data = future.result() print(data) print("last time :{}".format(time.time() - start_time)) # 2.6130592823028564
可以看到在耗cpu的應用中,多進程明顯優于多線程 2.6130592823028564 < 3.905290126800537
下面模擬一個io操作
# 多進程編程 # 耗cpu的操作,用多進程編程, 對于io操作來說,使用多線程編程 import time from concurrent.futures import ThreadPoolExecutor, as_completed from concurrent.futures import ProcessPoolExecutor def io_operation(n): time.sleep(2) return n if __name__ == '__main__': # 1. 對于耗cpu操作,多進程優于多線程 # with ThreadPoolExecutor(3) as executor: # all_task = [executor.submit(io_operation, num) for num in range(25, 35)] # start_time = time.time() # for future in as_completed(all_task): # data = future.result() # print(data) # print("last time :{}".format(time.time() - start_time)) # 8.00358772277832 # 多進程 ,在window環境 下必須放在main方法中執行,否則拋異常 with ProcessPoolExecutor(3) as executor: all_task = [executor.submit(io_operation, num) for num in range(25, 35)] start_time = time.time() for future in as_completed(all_task): data = future.result() print(data) print("last time :{}".format(time.time() - start_time)) # 8.12435245513916
關于“Python中多線程與多進程對比的示例分析”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。