Question

How to time your command and script execution in Linux?

Posted March 14, 2020 287 views
Linux BasicsLinux Commands

I was recently working on a script to migrate some large files from one server to another. I wanted to be able to tell how long the transfer took so that I could generate some reports for myself.

Here are a couple of ways on how to achieve that in Linux.

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

×
1 answer

For this example, I would use a rsync command, but this would work with any other command or set of commands as well.

  • Using the date command to print the time before and after my command. It would look something like this:
#!/bin/bash

start_time=$(date)

rsycn -avz /storage user@domain.com:/storage

end_time=$(date)

echo "Start time: ${start_time} - End time: ${end_time}"

That way you would able to tell when exactly my rsync process started and ended.

The output would look something like this:

Start time: Sat Mar 14 15:53:43 UTC 2020 - End time: Sat Mar 14 15:59:12 UTC 2020
  • Using the time command. This is a command which summarizes the time that it took for a specific script to run and the system resource usage.

If you decide to use the time command, the above script would change to:

#!/bin/bash

/usr/bin/time rsycn -avz /storage user@domain.com:/storage

The output, in this case, would look something like this:

real    0m10.004s
user    0m0.003s
sys     0m0.001s

The benefit of using time is that you could add different formatting strings so that you could get more information like the total number of CPU-seconds that the process spent in kernel mode, the total number of CPU-seconds that the process spent in user mode and more.

To do that you need to use the -f flag followed by the format, for example:

  • /usr/bin/time -f "%E real,%U user,%S sys" rsycn -avz /storage user@domain.com:/storage

This would give you the following output:

0:03.00 real,0.00 user,0.00 sys

For more information on the formatting strings that you could use, you could check out the man page here:

http://man7.org/linux/man-pages/man1/time.1.html

Share below if you are using any other methods of timing your scripts execution time!

Hope that this helps!
Regards,
Bobby

Submit an Answer