How to store a substring of the output of “time” f

2019-01-19 19:23发布

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

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

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

3条回答
做自己的国王
2楼-- · 2019-01-19 20:03

Using bash's built in string globbing you could do something like this:

output="real 0m0.002s
user 0m0.001s
sys  0m0.000s"

#get everything to the right of first "*user "
user=${output#*user }
#get everything to the left of the first "s*"
user=${user%%s*}
#get everythig to let left of "m*"
min=${user%%m*}
#get everything to the right of "*m" and left of ".*"
sec=${user#*m}
sec=${sec%%.*}
#get everything to the right of "*."
usec=${user#*.}


time=$[$usec + $sec * 1000 + $min * 60000]

Results running bash -x

+ output='real 0m0.002s
user 0m0.001s
sys  0m0.000s'
+ user='0m0.001s
sys  0m0.000s'
+ user=0m0.001
+ min=0
+ sec=0.001
+ sec=0
+ usec=001
+ time=1
查看更多
ら.Afraid
3楼-- · 2019-01-19 20:07

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.

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>&-

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

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}')

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

查看更多
啃猪蹄的小仙女
4楼-- · 2019-01-19 20:10

The clean way is to use the TIMEFORMAT shell variable to only print the user information. (man bash for more details.)

Then, of course you need to capture the output from it. This is impossible to do from the pipeline, as it's done internally by the shell, but you can run it in a subshell, and the output will go to standard error. But then you have to somehow redirect the output of the command elsewhere. Here, I just discard it, but many other possibilities exist, depending on exactly what you need to do. Then you need to munge d.ffffd into ffffdd. Just deleting the period will do so.

(TIMEFORMAT="%U"; time ls > /dev/null) |& tr -d .

If you like, you can add | sed s/^0*// to eliminate the leading zeroes.

%R will give real time, %S system time. You can change the precision with e.g. %6U to get microseconds, though most systems won't be anywhere near that accurate.

man bash for help on redirections. man tr and man sed for help on how to use them.

查看更多
登录 后发表回答