環境
windows10、 Vscode、 python 2.88
pythonで、下記のようにCSVファイルから行単位のデータを取り込んで
各行を並列に処理し、速度を上げたいと考えました。
threadとprocessでmapにより並列化しましたが、普通にloop処理した方が
10倍近く早く、逆に大幅に遅くなりました。
速度を上げたいのですが、どのような方法があるでしょうか?
python
1import time 2from concurrent.futures import ThreadPoolExecutor 3# from concurrent.futures import ProcessPoolExecutor 4 5def list_app(row): 6 d_row = row.split(',') 7 row = row + ',' + d_row[5] + ',' + d_row[6] + ',' + d_row[7] 8 return row 9 10if __name__=='__main__': 11 12 d_f_con=[] 13 thread_flag = True 14 15 with open('C:/Users/fxscX0cd6/Documents/test.csv','r',encoding='shift-jis') as f: 16 f_con=f.readlines() 17 18 startt = time.time() 19 20 if thread_flag == False: 21 for i,row in enumerate(f_con): 22 d_row = row.split(',') 23 row = row + ',' + d_row[5] + ',' + d_row[6] + ',' + d_row[7] 24 d_f_con.append(row) 25 26 else: 27 with ThreadPoolExecutor(max_workers=10) as executor: 28 # with ProcessPoolExecutor(max_workers=10) as executor: 29 results = executor.map(list_app, f_con) 30 results = list(results) 31 32 endt=time.time() -startt 33 34 print(endt)
threadとprocess仕様で1秒くらい、通常loopで0.1秒くらいでした。
速度を上げたい理由はなんでしょう?
・ファイルが大量にある
・実際のファイルのサイズはもっと大きい
・実際はもっと複雑な処理をしていて時間がかかっている
それによって、とれる方法が違ってくると思います。
> threadとprocess仕様で1秒くらい
マルチスレッドよりもマルチプロセスの方が、もっと遅くなりませんか?
(プロセスの生成の方が、スレッドの生成よりも時間がかかるため)
google colabで、
xxx = np.random.rand(100000, 10)
np.savetxt('test.csv', xxx, delimiter=',')
で作ったcsvファイルを使って質問のコードを実行したら、実行時間は下記の通りでした
並列化無し:0.2秒くらい
マルチスレッド:3秒くらい
マルチプロセス:30秒くらい
Pythonのバージョンはなにかの書き間違いですか? (それとも本当にPython2系を使っている? VS Codeのプラグインのバージョンを書いてしまったとかもありえる?)
追加: concurrent がある以上2系なはずはなかったですね