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
  • 193,181
  • 53
  • 473
  • 722
a06e
  • 12,613
  • 25
  • 66
  • 102
  • @l0b0 I'm not sure where to begin. I know how to sum two variables in bash, so if you teach me how to parse the output of `time` to get the two variables, `$sys` and `$user`, I can sum them – a06e May 14 '14 at 16:32

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
  • 9,700
  • 2
  • 38
  • 60
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
Sylvain Pineau
  • 61,564
  • 18
  • 149
  • 183
  • Is that in milliseconds? What if the command takes more than 1 second? – a06e May 14 '14 at 18:10
  • And how do I store the result in a variable? – a06e May 14 '14 at 18:15
  • I've updated my answer to store in a variable in ms – Sylvain Pineau May 14 '14 at 18:22
  • I'm aware this is askubuntu, but as a warning for folks like me: on macOS, `echo "2.577 + 0.164 * 1000" | bc -l ` actually evaluates to `166.577`. You need to explicitly insert the parentheses around the sum in order to get the right answer. – wen Jan 30 '17 at 18:07