Ubuntu – How to use time command in bash, to sum sys + user time, and output it as milliseconds

bashtime-command

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?

Best Answer

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