测量 bash 文件中的每个命令?

Soc*_*tes 4 command-line time bash

有没有办法测量 bash 文件中每个命令所花费的时间?因此,把时间放在每个命令的前面。命令的数量目前未知,因为我也打算将这个时间度量用于未来的 bash 脚本。还值得一提的是,我打算只运行具有 command1、command2、command3 等的简单 bash 脚本。因此,没有复杂的高级逻辑脚本。

假设我有一个类似于这个的 bash 文件:

#!/bin/bash

mv /path/to/file /other/path/
cd /other/path/
tar -xzf /other/path/file
Run Code Online (Sandbox Code Playgroud)

有没有办法获得与此类似的输出?

 6.553s   mv /path/to/file /other/path/
 0.057s   cd /other/path/
19.088s   tar -xzf /other/path/file
Run Code Online (Sandbox Code Playgroud)

我知道通过time我可以获得单个命令所花费的时间。但我正在寻找一种解决方案来测量每个命令本身的时间。

sud*_*dus 6

您可以使用/usr/bin/time-f以下示例类似的选项。在 shellscript 中的每个命令之前加上/usr/bin/time -f "%E %C"

$ /usr/bin/time -f "%E %C" sleep 2.34
0:02.34 sleep 2.34
Run Code Online (Sandbox Code Playgroud)

有关man time更多详细信息,请参阅。

例子:

我制作了一个小脚本,它可以通过识别命令来修改简单的shellscript,可以使用/usr/bin/time. 让我们使用名称time2script

#!/bin/bash

string='/usr/bin/time -f "%E %C"'

while IFS= read -r line
do
 cmd=$(<<< "$line" sed -e 's/ *//'|cut -d ' ' -f1)
 command=$(which "$cmd")
 if [ "$command" != "" ]
 then
  printf '%s %s\n' "$string" "$line"
 else
  printf '%s\n' "$line"
 fi
done < "$1"
Run Code Online (Sandbox Code Playgroud)

time2script在已编辑问题中的示例中使用:

$ ./time2script socrates1
#!/bin/bash

/usr/bin/time -f "%E %C" mv /path/to/file /other/path/
cd /other/path/
/usr/bin/time -f "%E %C" tar -xzf /other/path/file
Run Code Online (Sandbox Code Playgroud)

重定向以创建修改后的 shellscript,

./time2script socrates1 > socrates1-timing
Run Code Online (Sandbox Code Playgroud)