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?
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