I wish to find out how long an operation takes in a Linux shell script. How can I do this?
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.
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 .
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 .
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.
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.
Use the time
command. time ls /bin
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With