![見出し画像](https://assets.st-note.com/production/uploads/images/97458063/rectangle_large_type_2_07211fd898c32afd20dbc27d4588991b.jpeg?width=1200)
Python コピペで体験 並列処理!concurrent.futuresを最小構成で解説
Pythonの並列処理ライブラリであるconcurrent.futuresを利用方法・メリットを簡潔に記載します。
1.逐次処理
下記のような逐次処理のプログラムを実行した場合、合計何秒かかるでしょうか。
import time
def Kakurenbo():
time.sleep(5)
print("もういいかい?")
time.sleep(1)
print("まあだだよ?")
for i in range(16):
Kakurenbo()
約6秒かかる処理が16回実行されるため、合計96秒かかります。
2.並列処理
Pythonの並列処理ライブラリである、concurrent.futures(ThreadPoolExecutor)を利用した以下のコードの場合、何秒かかるでしょうか。
import os
import concurrent.futures
import time
def Kakurenbo():
time.sleep(5)
print("もういいかい?")
time.sleep(1)
print("まあだだよ?")
with concurrent.futures.ThreadPoolExecutor(max_workers=os.cpu_count()) as Thread:
for i in range(16):
Thread.submit(Kakurenbo)
16回の処理をCPUの数(スレッド数:今回は16スレッド)で処理しますので、16回の処理が合計約6秒で終了します。隠れんぼの隠れる側はたまったものじゃありませんね!!!