加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

解析Bash内置时间的输出

发布时间:2020-12-15 22:50:59 所属栏目:安全 来源:网络整理
导读:我正在从 Bash脚本运行一个C程序,并通过一个名为time的命令运行它,该命令输出一些运行算法的时间统计信息. 如果我要执行命令 time $ALGORITHM $VALUE $FILENAME 它产生输出: real 0m0.435suser 0m0.430ssys 0m0.003s 值取决于算法的运行 但是,我希望能够采
我正在从 Bash脚本运行一个C程序,并通过一个名为time的命令运行它,该命令输出一些运行算法的时间统计信息.

如果我要执行命令

time $ALGORITHM $VALUE $FILENAME

它产生输出:

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

值取决于算法的运行

但是,我希望能够采用0.435并将其分配给变量.
我已经读了一下awk,足以知道如果我把上面的命令输入awk,我应该能够抓住0.435并将它放在一个变量中.但是我该怎么做?

非常感谢

解决方法

你必须要小心:有Bash内置时间和外部命令时间,通常位于/usr/bin/time(类型类型 – 在系统上拥有所有可用时间的时间).

如果您的shell是Bash,那么当您发布时

time stuff

你在调用内置时间.如果没有一些小技巧,你不能直接捕捉时间的输出.这是因为时间不想干扰你可能会执行的重定向或管道,这是一件好事.

要获得标准输出的时间输出,您需要:

{ 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.

%%

06002

%[p][l]R

06003

%[p][l]U

06004

%[p][l]S

06005

%P

06006

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

$'nrealt%3lRnusert%3lUnsyst%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上.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读