krenkz
krenkz

Reputation: 470

How to get execution times of several commands only after a script is finished?

I am running a numbers of commands from a script and measuring the execution time (of only several of them). This I know how to do with time. But I also want to output all the times only after the whole script is finished (either in the shell or in a file). How do I do that?

EDIT: I am sorry, I should have specified that I am using a Fish shell.(Nevertheless, I will add bash to the tags so that other people can use the answers.)

Upvotes: 0

Views: 552

Answers (3)

user216
user216

Reputation: 156

option 1:

just try to run your script in this way:

time ./your_script.sh

https://www.cyberciti.biz/faq/unix-linux-time-command-examples-usage-syntax/

option 2:

npm install -g gnomon

./your_script.sh | gnomon

https://github.com/paypal/gnomon

Upvotes: 0

stark
stark

Reputation: 13189

Bash 4.2 and up have an obscure command for saving the unix time to a variable.

#!/bin/bash

# start time
printf -v s_time '%(%s)T' -1

# do stuff
sleep 1
sleep 2
sleep 3

# end time
printf -v e_time '%(%s)T' -1

# do more stuff
sleep 4

# print result
echo It took $(( e_time - s_time )) seconds

Shows the run time of the "do stuff" multiple commands

It took 6 seconds

Upvotes: 1

Grigoriy Sandu
Grigoriy Sandu

Reputation: 94

#!/bin/bash
#
declare -a toutput
declare -a commands
#
stime()
 {
  start=`date +%s`
  # run command
   $1
  end=`date +%s`
  toutput+=("$1 : $((end-start)) ,")
 }

# set array of commnds
commands+=("'ls -1 /var/log'")
commands+=("'sleep 3'")
commands+=("'sleep 5'")

echo "==================="
echo ${commands[@]}
echo "==================="

# execute commands and log times to toutput
#
for cc in "${commands[@]}"
  do
    stime "$(echo ${cc} | tr -d \')"
  done


echo "times = (" ${toutput[@]} ")"

Upvotes: 1

Related Questions