Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I measure duration in seconds in a shell script?

Tags:

shell

timing

I wish to find out how long an operation takes in a Linux shell script. How can I do this?

like image 841
yazz.com Avatar asked Mar 01 '11 09:03

yazz.com


People also ask

How do I count seconds in a Bash script?

Another (preferred) way to measure elapsed time in seconds in bash is to use a built-in bash variable called SECONDS . When you access SECONDS variable in a bash shell, it returns the number of seconds that have passed so far since the current shell was launched.

How do I convert time to seconds in Linux?

Method 1 – Using date In order to get the system date and time in seconds since 1970-01-01 00:00:00 UTC we use the command date +%s .

How does shell script calculate time difference?

For example if I run ` a=$(date +%s%N) sleep 1.235 b=$(date +%s%N) diff=$((b-a)) printf "%d. %d seconds passed\n" "${diff:0: -9}" "${diff: -9:3}" ` It says 1.241 seconds passed .

How does Bash script calculate time elapsed?

Using Bash Shell's TIMEFORMAT We should wrap our commands in time{} after we define the TIMEFORMAT string. The TIMEFORMAT is a string format that will be printed after the execution of the block code inside the time{} wrapper finishes. The %R specifies to print the elapsed time in seconds with milliseconds precision.


2 Answers

Using the time command, as others have suggested, is a good idea.

Another option is to use the magic built-in variable $SECONDS, which contains the number of seconds since the script started executing. You can say:

START_TIME=$SECONDS dosomething ELAPSED_TIME=$(($SECONDS - $START_TIME)) 

I think this is bash-specific, but since you're on Linux, I assume you're using bash.

like image 183
Tom Anderson Avatar answered Oct 12 '22 17:10

Tom Anderson


Use the time command. time ls /bin.

like image 25
Keith Avatar answered Oct 12 '22 16:10

Keith