measure execution time in bash
While working in bash, quite often I need to launch scripts/programs that take some time to finish. I would like to have an idea how much time it took. How to do it?
Solution #1 and #2 (easy to forget)
In Unix, there is a command called
time, which can measure the execution time of a process. Example:
$ time sleep 3 real 0m3.001s user 0m0.000s sys 0m0.001s
Nice, but you don’t want to start everything with
time, do you?
Another way is to print the date before and after the process:
$ date; echo "serious calculation in progress..."; sleep 3; date Tue May 13 11:40:42 CEST 2014 serious calculation in progress... Tue May 13 11:40:45 CEST 2014
Now you can see when the process started and when it finished.
Fine, but… What if you start a process normally and then you realize after a few minutes that it won’t finish soon. Stop it and restart it with one of the aforementioned two methods? No. You wait until it stops and if you are not at the computer, you won’t have any idea how long it was running. Damn!
Is there an easy solution for this problem? A painless, straightforward way? Well, yes, there is. See below.
Solution #3 (the easy way)
In bash, you can customize the prompt via the
PS1 variable. By default, its value is set to something similar:
$ export PS1="\u@\h:\w\$ " jabba@nancy:~$ cd /trash/ jabba@nancy:/trash$
All we need to do is add the time in the prompt. Then, when a process terminates, you will see right away when it stopped. For adding the time, simply insert “
$ export PS1="\u@\h [\t] \w\$ " jabba@nancy [11:52:20] ~$ cd /trash jabba@nancy [11:52:29] /trash$
This is the basic version. In addition, my prompt is colored. To have a colored prompt, I include a file in my
.bashrc. Thus, the end of my
.bashrc looks like this:
# this is the last line in my .bashrc: source ~/.bash_prompt
You can find my
.bash_prompt file here.