Joblibを利用して処理を並列化してみる
PythonでのJoblibを利用する事で並列処理が容易に記述できるので、その手順についてのメモ
Install
pip
コマンドを利用してインストール
> pip install joblib
並列処理のお試し
まずは、モジュールのインポート
時間計測用にelapsed_time
も定義しておく
import time
from joblib import Parallel, delayed
def elapsed_time(func):
print(f"Function name: {func.__name__}")
start = time.time()
result = func()
print(result)
elapsed = time.time() - start
print(f"Elapsed: {elapsed}")
print('-' * 20)
時間のかかる適当な処理
時間計測をするために適当な計算を実行する
def test_func():
result = 0
for i in range(10 ** 7):
result += 1
return result
そのまま実行
順番に10回実行する場合
def normal():
result = 0
for i in range(10):
result += test_func()
return result
並列に実行
joblib
で並列化を行う場合、実行する関数をdelayed
でラップしたものをリスト等として準備する必要がある
ここでは、test_func()を10回実行するため、リスト内包表記で10個分の要素を作成
jobs = [delayed(test_func)() for i in range(10)]
jobs
リストの中身はこんな具合
print(jobs)
[(<function test_func at 0x7fa94f117700>, (), {}), (<function test_func at 0x7fa94f117700>, (), {}), (<function test_func at 0x7fa94f117700>, (), {}), (<function test_func at 0x7fa94f117700>, (), {}), (<function test_func at 0x7fa94f117700>, (), {}), (<function test_func at 0x7fa94f117700>, (), {}), (<function test_func at 0x7fa94f117700>, (), {}), (<function test_func at 0x7fa94f117700>, (), {}), (<function test_func at 0x7fa94f117700>, (), {}), (<function test_func at 0x7fa94f117700>, (), {})]
これをParallel
で並列処理
def parallel():
jobs = [delayed(test_func)() for i in range(10)]
result = Parallel(n_jobs=-1)(jobs)
return result
n_jobs
で並列ジョブの数を指定
-1
を指定するとシステムに合わせた最大値となる
オーバヘッドの少ない並列処理
コンテキストマネージャーを利用して実行
def parallel_reuse():
result = None
jobs = [delayed(test_func)() for i in range(10)]
with Parallel(n_jobs=-1) as p:
result = p(jobs)
return result
並列処理の実行
それぞれの処理を呼び出す部分を追記
if __name__ == "__main__":
elapsed_time(normal)
elapsed_time(parallel)
elapsed_time(parallel_reuse)
実行結果は下記の通り
Function name: normal
100000000
Elapsed: 4.5094709396362305
--------------------
Function name: parallel
[10000000, 10000000, 10000000, 10000000, 10000000, 10000000, 10000000, 10000000, 10000000, 10000000]
Elapsed: 1.9986412525177002
--------------------
Function name: parallel_with_reuse
[10000000, 10000000, 10000000, 10000000, 10000000, 10000000, 10000000, 10000000, 10000000, 10000000]
Elapsed: 1.7216787338256836
--------------------
Macbook Air上で実行しているために、負荷がかかるとCPUの温度が上昇し、駆動周波数が低下するので計算速度はおちてしまうが、並列化の効果がちょっと見える
今回はここまで