如何存储“时间"输出的子字符串? bash脚本中的功能 [英] How to store a substring of the output of "time" function in bash script

查看:59
本文介绍了如何存储“时间"输出的子字符串? bash脚本中的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此bash的内置时间函数应以这种格式输出

So the built-in time function for bash should output in this format

real 0m0.002s
user 0m0.001s
sys  0m0.000s

我想以毫秒为单位节省用户时间,例如001,这是一种干净的方法吗?

I want to save the user time in milliseconds, like 001 what's a clean way to do this?

推荐答案

Bash的time内置捕获起来有些棘手,因为它具有特殊的处理方式,因此它可以返回整个管道的处理时间,例如time ls -l | sort | uniq而不是我的示例中仅ls -l命令的处理时间.

Bash's time builtin is a bit tricky to capture because it has special handling so that it can return the processing time for an entire pipeline like time ls -l | sort | uniq rather than just the processing time for only the ls -l command in my example.

捕获 just 时间输出的最佳方法是以下重定向技术:

The best way to capture just the output of time is the following redirection technique:

exec 3>&1 4>&2
foo=$( { time some_command 1>&3 2>&4; } 2>&1 ) # change some_command
exec 3>&- 4>&-

在这一点上,如果您要使用echo "$foo",将会看到

At this point if you were to echo "$foo" you would see something on the order of

real    0m0.013s
user    0m0.004s
sys     0m0.007s

现在只获得其中的004部分,您可以有很多选择:sed,awk或bash来命名前3名.我个人最喜欢的是awk,看起来像这样:

Now to get just the 004 part of that you have quite a few options: sed, awk or straight bash to name the top 3. My personal favorite would be awk and it would look something like this:

foo=$({ time some_command 1>&3 2>&4;} 2>&1 | awk -F'[s.]' '/user/{print $3}')

现在,如果您要使用echo "$foo",则只会看到所需的004

Now if you were to echo "$foo" you would see just 004 as desired

这篇关于如何存储“时间"输出的子字符串? bash脚本中的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆