0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

bash組み込みのtimeコマンドでrealの時間のみを取得したい

Posted at

bashでtimeコマンドを実行する場合。

shellに組み込みされているtimeコマンドがありますが。
それ以外にも外部コマンドとしてgnuが提供しているtimeコマンドもインストールされており。

gnu版timeコマンドもインストールされている場合などで、単純にtimeとしてコマンドを実行すると、bash組み込みのtimeが優先して実行されます。
なおbash組み込みのtimeコマンドとgnu版timeコマンドではパラメータや出力結果が異なります。

今回は実行ログなどへの処理時間のみの書き込みを想定して、shell組み込みのbashコマンドの実行結果から実行時間のみ取得する方法について説明します。

組み込み版timeの出力について

組み込み版timeを利用してsleep 2を実行し場合の出力は下記画像のようになります。

image.png

bash組み込みのtimeコマンドは実行結果を標準エラーに出力するのでリダイレクトしてgrepに渡して、ログに書き込みしている。

余談 helpとman

timeコマンドの使い方を調べる際に、man help とするとgnu版の説明がでてくるので。
built-in版の説明を調べたい場合はhelpコマンドを利用しましょう。

timeコマンドが2種類ある事をしらないと、ここらへん混乱するので注意。

man time

image.png

help time

image.png

timeコマンド実行結果から実行時間のみを取得

helpで説明を確認すると、組み込み版timeコマンドではフォーマットを指定して出力すうようなオプションはないので、出力結果から実行時間を抽出します。


# 組み込み版timeコマンドはエラー出力に結果出力するのでエラー出力を標準出力にも出力するようにリダイレクト
# grepとawkを利用して出力結果をフィルタ
{ time -p sleep 2 ; } 2>&1 | grep 'real' | awk '{ print $2 }'

# 組み込み版timeコマンドはエラー出力に結果出力するのでエラー出力を標準出力にも出力するようにリダイレクト
# awkを利用して出力結果をフィルタ
{ time -p sleep 2 ; } 2>&1 | awk '/real/ {print $2}'

image.png

総評

bashを利用する際に、built-inコマンドのtimeを実行しているのか、外部コマンドのtimeを実行しているのか。
その存在を理解していないと、意外と混乱する気がします。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?