Parsing the output of Bash's time builtin -
i'm running c program bash script, , running through command called time, outputs time statistics running of algorithm.
if perform command
time $algorithm $value $filename it produces output:
real 0m0.435s user 0m0.430s sys 0m0.003s the values depending on running of algorithm
however, able take 0.435 , assign variable. i've read awk bit, enough know if pipe above command awk, should able grab 0.435 , place in variable. how do that?
many thanks
you must careful: there's bash builtin time , there's external command time, located in /usr/bin/time (type type -a time have available times on system).
if shell bash, when issue
time stuff you're calling builtin time. can't directly catch output of time without minor trickery. because time doesn't want interfere possible redirections or pipes you'll perform, , that's thing.
to time output on standard out, need:
{ time stuff; } 2>&1 (grouping , redirection).
now, parsing output: parsing output of command bad idea, when it's possible without. fortunately, bash's time command accepts format string. manual:
timeformatthe value of parameter used format string specifying how timing information pipelines prefixed time reserved word should displayed.
%character introduces escape sequence expanded time value or other information. escape sequences , meanings follows; braces denote optional portions.
%%literal `%`.
%[p][l]relapsed time in seconds.
%[p][l]unumber of cpu seconds spent in user mode.
%[p][l]snumber of cpu seconds spent in system mode.
%pcpu percentage, computed (%u + %s) / %r.the optional
pdigit specifying precision, number of fractional digits after decimal point. value of 0 causes no decimal point or fraction output. @ 3 places after decimal point may specified; values of p greater 3 changed 3. ifpnot specified, value 3 used.the optional
lspecifies longer format, including minutes, of formmmmss.ffs. value ofpdetermines whether or not fraction included.if variable not set, bash acts if had value
$'\nreal\t%3lr\nuser\t%3lu\nsys\t%3ls'if value null, no timing information displayed. trailing newline added when format string displayed.
so, achieve want:
var=$(timeformat='%r'; { time $algorithm $value $filename; } 2>&1) as @glennjackman points out, if command sends messages standard output , standard error, must take care of too. that, plumbing necessary:
exec 3>&1 4>&2 var=$(timeformat='%r'; { time $algorithm $value $filename 1>&3 2>&4; } 2>&1) exec 3>&- 4>&- source: bashfaq032 on wonderful greg's wiki.
Comments
Post a Comment