gpt4 book ai didi

bash - 解析 Bash 时间内置函数的输出

转载 作者:行者123 更新时间:2023-11-29 09:01:33 27 4
gpt4 key购买 nike

我正在从 Bash 脚本运行 C 程序,并通过名为 time 的命令运行它,该命令输出算法运行的一些时间统计信息。

如果我要执行命令

time $ALGORITHM $VALUE $FILENAME

它产生输出:

real    0m0.435s
user 0m0.430s
sys 0m0.003s

值取决于算法的运行

但是,我希望能够做的是获取 0.435 并将其分配给一个变量。我已经读了一点 awk,足以知道如果我将上面的命令通过管道传输到 awk,我应该能够获取 0.435 并将它放在一个变量中。但我该怎么做呢?

非常感谢

最佳答案

你必须小心:有 Bash 内置的 time 和外部命令 time,通常位于 /usr/bin/time (键入 type -a time 以获得系统上所有可用的 time)。

如果你的 shell 是 Bash,当你发出

time stuff

你正在调用内置的 time。如果不使用一些小技巧,您无法直接捕获 time 的输出。这是因为 time 不想干扰您将执行的可能的重定向或管道,这是一件好事。

要在标准输出上获得 time 输出,您需要:

{ time stuff; } 2>&1

(分组和重定向)。

现在,关于解析输出:解析命令的输出通常不是一个好主意,尤其是在可以不解析的情况下。幸运的是,Bash 的 time 命令接受格式字符串。来自手册:

TIMEFORMAT

The value of this parameter is used as a format string specifying how the timing information for pipelines prefixed with the time reserved word should be displayed. The % character introduces an escape sequence that is expanded to a time value or other information. The escape sequences and their meanings are as follows; the braces denote optional portions.

%%

   A literal `%`.

%[p][l]R

   The elapsed time in seconds.

%[p][l]U

   The number of CPU seconds spent in user mode.

%[p][l]S

   The number of CPU seconds spent in system mode.

%P

   The CPU percentage, computed as (%U + %S) / %R. 

The optional p is a digit specifying the precision, the number of fractional digits after a decimal point. A value of 0 causes no decimal point or fraction to be output. At most three places after the decimal point may be specified; values of p greater than 3 are changed to 3. If p is not specified, the value 3 is used.

The optional l specifies a longer format, including minutes, of the form MMmSS.FFs. The value of p determines whether or not the fraction is included.

If this variable is not set, Bash acts as if it had the value

$'\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS'

If the value is null, no timing information is displayed. A trailing newline is added when the format string is displayed.

所以,要完全实现你想要的:

var=$(TIMEFORMAT='%R'; { time $ALGORITHM $VALUE $FILENAME; } 2>&1)

作为@glennjackman指出,如果您的命令向标准输出和标准错误发送任何消息,您也必须注意这一点。为此,需要一些额外的管道:

exec 3>&1 4>&2
var=$(TIMEFORMAT='%R'; { time $ALGORITHM $VALUE $FILENAME 1>&3 2>&4; } 2>&1)
exec 3>&- 4>&-

来源: BashFAQ032关于精彩Greg's wiki .

关于bash - 解析 Bash 时间内置函数的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26784870/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com