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

joe
  • 25
  • 3

2 Answers2

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.

glenn jackman
  • 84,176
  • 15
  • 116
  • 168
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)?

cas
  • 1
  • 7
  • 119
  • 185
ibuprofen
  • 2,781
  • 1
  • 14
  • 33
  • 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. – cas Jun 01 '21 at 04:36