2

The time command returns a table like this?

real      0m1.607s
user    0m0.154s
sys 0m0.032s

I am running this inside a shell script. What's the simplest way to process time output so that I get a variable $RUNTIME which holds the sum user + sys in milliseconds?

muru
  • 207,228
a06e
  • 14,233

2 Answers2

2

Do this

Run your command using below script, substitute your_command.

$ ALL_TIME=`(time your_command) 2>&1 | grep -E "user|sys" | sed s/[a-z]//g`

now variable ALL_TIME store two values: `

$ echo $ALL_TIME
00.001 00.003

Now you need to summarize values. Use script below

Don't forget to set RUNTIME to zero.

$ RUNTIME=0
$ for i in $ALL_TIME; do RUNTIME=`echo "$RUNTIME + $i"|bc`; done
$ echo $RUNTIME
.004

Sources

How to grep from time

Redirect output of time command in unix into a variable in bash?

c0rp
  • 10,010
2

If you need to use bash time builtin function I'd use the following command:

a=$(echo $( TIMEFORMAT="%3U + %3S"; { time your_command; } 2>&1) "*1000" | bc -l)

Examples:

a=$(echo $( TIMEFORMAT="%3U + %3S"; { time sleep 1; } 2>&1) "*1000" | bc -l)
echo $a
2.000

a=$(echo $( TIMEFORMAT="%3U + %3S"; { time sudo hdparm -t -T /dev/sda 2>&1 >/dev/null; } 2>&1) "*1000"  | bc -l)
echo $a
2302.137