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

后端 未结 5 675
走了就别回头了
走了就别回头了 2021-02-04 17:15

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?

5条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-04 17:52

    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
    

提交回复
热议问题