Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

time

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?

like image 940
flybywire Avatar asked May 13 '09 15:05

flybywire


1 Answers

Are you wanting to put this code in your script, or do it from the process that starts the script?

For the latter, you can use the "time" reserved word and then parse what it returns to get how much time a script takes.

If you want to do this from within a script you can set the variable SECONDS to zero, and each time thereafter that you reference that variable it will be updated to be the number of elapsed seconds. So, you can put "SECONDS=0" at the very start of your script, and whenever you need the elapsed time it will be in the SECONDS variable.

You can also use the $SECONDS trick on the command line as well, for example:

$ SECONDS=0; sleep 5 ; echo "that took approximately $SECONDS seconds"

The time reserved word and the SECONDS variable are both documented in the bash man page.

like image 98
Bryan Oakley Avatar answered Oct 14 '22 05:10

Bryan Oakley