LoginSignup
4
3

More than 5 years have passed since last update.

シェルスクリプトで大量にechoすると遅い

Last updated at Posted at 2017-06-09

1〜500000を出力するプログラムを、bashとrubyで比較してみました。
bashとrubyのバージョンはそれぞれ 4.3.48 と 2.4.0 です。

$ time for i in {1..500000}; do echo $i > /dev/null; done

real    0m5.426s
user    0m4.212s
sys 0m1.168s
$ time ruby -e '1.upto(500000) {|i| puts i}' > /dev/null

real    0m0.537s
user    0m0.496s
sys 0m0.004s

10倍もの差がつきました。

echoを50万回起動するのが遅いんでしょうかね?
あるいはrubyは出力をバッファリングしているはずですが、bashはしていないから?

繰り返しの回数をいろいろ変えてみたところ、1000回程度の繰り返しなら外部コマンド起動のオーバーヘッドのほうが大きいようで、for+echoが早いですが、10000回で同じくらいの実行時間になりました。

数万回の繰り返しになってくると、echoをforで回すのはやめたほうが良さそうです。

4
3
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
4
3