【问题标题】:How to get execution times of several commands only after a script is finished?如何仅在脚本完成后获取多个命令的执行时间?
【发布时间】:2021-05-10 11:17:14
【问题描述】:

我正在从一个脚本运行许多命令并测量执行时间(其中只有几个)。我知道如何处理time。但我也想在整个脚本完成后(在 shell 或文件中)一直输出。我该怎么做?

编辑: 对不起,我应该指定我使用的是 Fish shell。(不过,我会将 bash 添加到标签中,以便其他人可以使用答案。)

【问题讨论】:

标签: linux bash shell time fish


【解决方案1】:
#!/bin/bash
#
declare -a toutput
declare -a commands
#
stime()
 {
  start=`date +%s`
  # run command
   $1
  end=`date +%s`
  toutput+=("$1 : $((end-start)) ,")
 }

# set array of commnds
commands+=("'ls -1 /var/log'")
commands+=("'sleep 3'")
commands+=("'sleep 5'")

echo "==================="
echo ${commands[@]}
echo "==================="

# execute commands and log times to toutput
#
for cc in "${commands[@]}"
  do
    stime "$(echo ${cc} | tr -d \')"
  done


echo "times = (" ${toutput[@]} ")"

【讨论】:

    【解决方案2】:

    Bash 4.2 及更高版本有一个晦涩的命令,用于将 unix 时间保存到变量中。

    #!/bin/bash
    
    # start time
    printf -v s_time '%(%s)T' -1
    
    # do stuff
    sleep 1
    sleep 2
    sleep 3
    
    # end time
    printf -v e_time '%(%s)T' -1
    
    # do more stuff
    sleep 4
    
    # print result
    echo It took $(( e_time - s_time )) seconds
    

    显示“do stuff”多个命令的运行时间

    It took 6 seconds
    

    【讨论】:

    • 不错。我不知道 printf 内置的这个新功能。每天学习一些东西!
    【解决方案3】:

    选项 1:

    尝试以这种方式运行您的脚本:

    time ./your_script.sh
    

    https://www.cyberciti.biz/faq/unix-linux-time-command-examples-usage-syntax/

    选项 2:

    npm install -g gnomon
    
    ./your_script.sh | gnomon
    

    https://github.com/paypal/gnomon

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-05
      • 2023-04-06
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 2012-05-17
      • 1970-01-01
      相关资源
      最近更新 更多