Alex Rivera | Logout

Save in a variable the number of seconds a process took to run

Asked 2009-05-13T15:16:14.673
9

I want to run a process in bash and save in an env variable the number of seconds it took to run. How would I do such a thing?

Edit
Report

2 Answers

8

This works in Bash, and also Zsh:

# Set time format to seconds
TIMEFORMAT=%R
# Time a process
PROC_TIME=$(time (insert command here >/dev/null 2>&1) 2>&1)
echo $PROC_TIME
  • The first two redirections hide your process's output ">/dev/null 2>&1"
  • The last redirect is needed because "time" prints the time on stderr
answered 2009-05-13T15:32:35.147
0

Using GNU time,

\time -p -o time.log $COMMAND

and then read time.log.

(Use either \time or command time, otherwise you'll be using Bash's time built-in, which doesn't support these options.)

This will work even when $COMMAND prints to stderr (which would confuse Oli's answer), and keeps stdout/stderr (which Farzy's answer doesn't).

-o ... tells time to send its output to a file rather than to stderr (as is the default), and -p generates the traditional

real 0.00
user 0.00
sys 0.00

rather than GNU time's default of

0.00user 0.00system 0:00.01elapsed 8%CPU (0avgtext+0avgdata 0maxresident)k
80inputs+0outputs (1major+188minor)pagefaults 0swaps
answered 2009-05-13T15:40:26.477

Your Answer