【问题标题】:How to get the output of time command in a bash script?如何在 bash 脚本中获取 time 命令的输出?
【发布时间】:2015-12-17 01:34:32
【问题描述】:

此命令在我的 shell 中完美运行,我想在 bash 脚本中编写它,但它不再起作用了:

make -s clean > /dev/null; { time make -j -s gallery > /dev/null; } 2>&1 | grep real | sed 's/^.*m//;s/.$/ /' > time_make 

问题在于时间的输出。

在 shell 中这个命令:

make -s clean > /dev/null; { time make -j 1 -s gallery > /dev/null; } 2>&1 | grep m > time_make

有结果:

real   0m2.127s
user   0m3.375s
sys    0m0.532s

这很好。

但是在脚本中(#!/bin/sh):

相同的命令有结果:

3.36user 0.51system 0:02.08elapsed 186%CPU (0avgtext+0avgdata49100maxresident)k
0inputs+2384outputs (0major+114980minor)pagefaults 0swaps

如何在bash脚本中获取“real”的值?

我真的不明白为什么“时间”命令的输出不同。谁能帮帮我?

提前致谢。

【问题讨论】:

  • 尝试显式运行/usr/bin/time
  • 啊....它给了我我不想要的。谢谢,所以另一个应该是....嗯,我尝试了“whereis time”给出的另一个,但我没有找到一个好的
  • 使用which time 找出正在使用的内容。它可能是 shell 的一部分,根本不是命令。
  • 它给了我你说的那个,
  • 如果您阅读 Bash 的手册页,您会发现它提供了自己的时间。对于 POSIX 样式的输出,只有一个选项 time -p。也许这就是你所追求的?

标签: bash shell time output io-redirection


【解决方案1】:

如果您想在 bash 中捕获命令所花费的时间,您可以通过执行以下操作来获得更多控制权(假设您在安装了 GNU 时间的系统上):

START=$(date +%s.%N)
# command you want to time goes here
END=$(date +%s.%N)
printf -v DELTA "%g" $(bc <<<"$END - $START")
echo "Command took ${DELTA} seconds"

您实际上可以将输出格式化为小时、分钟、秒等。

【讨论】:

    猜你喜欢
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 2012-09-26
    • 2020-04-30
    相关资源
    最近更新 更多