bash ループ中のリダイレクトはまとめた方が高速になる

2011-2-11 01:21
このエントリーをはてなブックマークに追加

bash の出力をファイルに行なう際、ループ中で毎回 echo のたびにリダイレクトをすると遅いのではないかと思い検証してみた。

#! /bin/bash -
## test1.sh
echo '' > output1.dat
for i in {0..99999}
do
        echo $i >> output1.dat
done
$ time ./test1.sh

real    0m3.003s
user    0m2.364s
sys     0m0.638s

これをループのブロックごとリダイレクトさせると高速になる。

#! /bin/bash -
## test2.sh
for i in {0..99999}
do
        echo $i 
done > output2.dat
$ time ./test2.sh

real    0m0.841s
user    0m0.537s
sys     0m0.305s

ちなみにブロックごとリダイレクトしていても、ループ中で別のリダイレクトしたい場合は個別に書けば優先されるので問題ない。

ループに限らず { } で囲んだブロックをまるごとリダイレクトできる。

 output3.dat
  • ブックマーク : アクセス: 24,339回
  • カテゴリー : Linux
  • キーワード :

コメントはまだありません

No comments yet.

Sorry, the comment form is closed at this time.

33 queries. HTML convert time: 0.090 sec. Powered by WordPress. Valid XHTML
Copyright © 2003-2017 @ futuremix.org ログイン