0

i need to get the running time of a program as soon as it is closed and i came up with this

start=`date +"%M"`
while [ `pgrep vlc` ];do
        echo vlcopen > /dev/null
done
stop=`date +"%M"`

[ $stop -lt $start ]&&time=$[ 60-$start+$stop ]||time=$[ $stop-$start ]
echo $time > time.txt

and it does the job but this is highly inefficient and takes a lot of cup usage how do i do this more efficiently

1
  • Read man time. We have a tool for that. Commented May 31, 2021 at 18:10

2 Answers 2

2

One option is to use time

Note: Bash has a keyword time so if you do:

time some command

that one is used , SHELL_GRAMMAR: bash

The time you find in man time is usually something like /usr/bin/time

$ type -t time
keyword

Main point in using the non bash time is features like -v (GNU time).

Also see: What do 'real', 'user' and 'sys' mean in the output of time(1)?

1
  • 1
    BTW, you can change the output format of bash's built-in time with the TIMEFORMAT variable. e.g. TIMEFORMAT=$'\nreal %3lR\tuser %3lU\tsys %3lS' is, IMO, a nice simple one-line format (I set this in my ~/.bashrc). The GNU version of /usr/bin/time (i.e. not the bash built-in) uses the TIME variable instead. Commented Jun 1, 2021 at 4:36
2

Use the bash SECONDS variable:

SECONDS=0

# do stuff here, such as
sleep 5

duration=$SECONDS

echo "The stuff took $duration seconds to complete"

Efficiency is gained by removing the need to spawn external processes.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.