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:

timeformat

the 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]r

   elapsed time in seconds. 

%[p][l]u

   number of cpu seconds spent in user mode. 

%[p][l]s

   number of cpu seconds spent in system mode. 

%p

   cpu percentage, computed (%u + %s) / %r.  

the optional p digit 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. if p not specified, value 3 used.

the optional l specifies longer format, including minutes, of form mmmss.ffs. value of p determines 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

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -