LoginSignup
1
2

More than 1 year has passed since last update.

xargsによる連番ファイルの並列化(ワンライナー)

Last updated at Posted at 2021-11-02

xargsで連番ファイルを容易に並列処理できるのでそのメモ。
連番で命名された画像ファイルの一括処理などに利用可能。

ここでは、0001.txt, 0002.txt, ..., 9999.txtを
0001.dat, 0002.dat, ..., 9999.datにリネームする1

for each in {0001..9999}; do echo $each;done | xargs -P 20 -n1 -I{} mv {}.dat {}.txt

とすればプロセス数20で並列化されてmv $each.dat $each.txtコマンドが動く。
この例ではうまみはないものの、CPU時間を消費するものには並列効果がある。

もう少し実用的な例として、512枚のpdfファイルpngに変換する作業の高速化率を示す。
mogrifyで

time mogrify -density 300 -format png 300 {001..512}.pdf

とすると、1分48秒かかる処理が

time for each in {001..512}; do echo $each;done | xargs -P 48 -n1 -I{}  convert -density 300 {}.pdf {}.png

では3.7秒で終了し、
30倍程度の速度が出ている2
1分の処理が2秒に短縮されてもそう嬉しくないが、1時間を2分にできると思えば価値は高い。

なお、-Pの引数で並列化数を変更でき、-P 1とすると

time for each in {001..512}; do echo $each;done | xargs -P 1 -n1 -I{} convert -density 300 {}.pdf {}.png

1分53秒かかり、当たり前だが、mogrify と時間はほとんど変わらない。

参考
https://orebibou.com/ja/home/201507/20150727_001/
https://qiita.com/knknkn1162/items/806604341508d32b160e
https://qiita.com/shungok/items/f852be01f08568991f18
https://qiita.com/SUZUKI_Masaya/items/a58523c4e4c8b3a2958c


  1. この操作であれば、rename s/txt/dat/ ????.txtでよい。あくまで例示です。 

  2. 最適な並列数は環境依存です。CPUのコア数くらいまでしか速度は出ないでしょう。試した環境はハイパースレッディング込みで48コア。 

1
2
1

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
1
2