このすみノート

Webエンジニアが技術や趣味を書くブログです。

timeコマンドの出力内容が、bashとzshで異なる

サーバー上で時間のかかるスクリプトを実行する時に、実行時間の計測目的でtimeコマンドを使っています。

この前たまたまMacBook上でtimeコマンドを実行した時に、出力内容が異なることに気づきました。

bash-3.2$ time sleep 1

real    0m1.009s
user    0m0.003s
sys 0m0.005s
bash-3.2$ zsh
% time sleep 1
sleep 1  0.00s user 0.00s system 0% cpu 1.006 total

bashとzshで異なる点

  • bashでは時間が出ます。
  • zsh (MacBook) では時間以外も表示されているようです。

クラメソに記事がありました。

dev.classmethod.jp

zshでは、TIMEFMTが表示内容を定めている

手元のzsh上で確認しました。

echo $TIMEFMT
%J  %U user %S system %P cpu %*E total

説明を読むに%*Eは‘hh:mm:ss.ttt’フォーマットなので、time sleep 1は1.006秒という結果になります。

  • %J : The name of this job.
  • %U : CPU seconds spent in user mode.
  • %S : CPU seconds spent in kernel mode.
  • %P : The CPU percentage, computed as 100*(%U+%S)/%E.
  • %E : Elapsed time in seconds.
  • A star may be inserted between the percent sign and flags printing time (e.g., ‘%*E’); this causes the time to be printed in ‘hh:mm:ss.ttt’ format (hours and minutes are only printed if they are not zero). Alternatively, ‘m’ or ‘u’ may be used (e.g., ‘%mE’) to produce time output in milliseconds or microseconds, respectively.

https://zsh.sourceforge.io/Doc/Release/Parameters.html

zshのTIMEFMTを変えて実行してみる

%* で時間表記になるので、それを使うとbashに近づきます。

% TIMEFMT="real %*Es user %*Us system %*Ss"; time sleep 1
real 1.010s user 0.002s system 0.003s

あとがき

bashとzshは細部でも意外と異なることを実感しました。