LoginSignup
16
14

More than 5 years have passed since last update.

starmapでPythonでの並列処理の結果をリストで受け取る

Posted at

はじめに

  • pythonの並列処理といえばmultiprocessモジュール
  • 結果がリストで欲しいときは、mapを使う
  • しかし、mapでは、複数の引数を渡すことができないみたいです
    • 機械学習等の数値実験用に、引数を色々変えて実験することが多いため、一つはちょっと。。
  • Python 2.X では、mapに複数の引数を渡すために、wrapper関数を定義してそれを渡すように記述する必要があったが、Python 3.3 以降は starmapでもっと楽に記述できるようになった
  • starmapの使い方の自分メモです

サンプルコード

#!/usr/bin/env python3
from itertools import product
from multiprocessing import Pool

# 並列処理したい関数
def multi_test(arg1, arg2, arg3):
    return(arg1+arg2+arg3)

# 並列数を決めて、Poolを用意
pool = Pool(3)

# 引数のバリエーションをタプルのリストで用意
multi_args = []
for iter1, iter2, iter3 in product(range(1,4), range(1,4), range(1,4)):    
    multi_args.append((iter1,iter2,iter3))
print(multi_args)    
[(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 1), (1, 3, 2), (1, 3, 3), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 3, 1), (3, 3, 2), (3, 3, 3)]

# 並列処理実行
results = pool.starmap(multi_test, multi_args)  
print(results)
[3, 4, 5, 4, 5, 6, 5, 6, 7, 4, 5, 6, 5, 6, 7, 6, 7, 8, 5, 6, 7, 6, 7, 8, 7, 8, 9]

おわりに

  • シンプルに記述できた。使い始めたばかりですので、おかしいところは教えてください。

参考

16
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
14