bash time - ghdrako/doc_snipets GitHub Wiki

bash built-in variable SECONDS

Each time you reference the variable it will return the elapsed time since the script invocation.

echo "Start $SECONDS"
sleep 10
echo "Middle $SECONDS"
sleep 10
echo "End $SECONDS"

Output:
Start 0
Middle 10
End 20

time - build-in bash comand

TIMEFORMAT

Value Description
%% A literal %.
%[p][l]R The elapsed time in seconds.
%[p][l]U The number of CPU seconds spent in user mode.
%[p][l]S The number of CPU seconds spent in system mode.
%P The CPU percentage, computed as (%U + %S) / %R.

The optional p is a digit specifying the precision, the number of fractional digits after a decimal point. A value of 0 causes no decimal point or fraction to be output. At most three places after the decimal point may be specified; values of p greater than 3 are changed to 3. If p, is not specified, the value 3 is used. The optional l specifies a longer format, including minutes, of the form MMmSS.FFs. The value of p determines whether or not the fraction is included.

time command
$ cat elapsed_time.sh
TIMEFORMAT='It took %R seconds.'
time {
sleep 5
sleep 7
}

$./elapsed_time.sh
It took 12.008 seconds.
TIMEFORMAT='%3R'  # The number specifies the precision and can range from 0 to 3 (the default). Format output 5.009 65.233
TIMEFORMAT='%3lR' # l gives long format Format output 3m10.022s
# Time format changes
TIMEFORMAT='%E elapsed'

# Function to be profiled
optimize_function() {
  sleep 2
}

# Profile the function execution
time optimize_function

time external command

/usr/bin/time -f'%E' $CMD