Determine amount of time to process

Hello all,

Hopefully someone can point me in the right direction...
I have a script written in bash which is pretty basic and just stop/starts various services based on particular conditions. What I am trying to build is a reporting type function which will send out an email with various stats and one of which I would like to include is the amount of time it took for the various condition to complete..

My initial thoughts were to assign the current system date to a variable at the beginning of the condition and then once complete assign the date to a new variable, compare the difference and then I would have my answer...

Does anyone have any sample script that would work in this situation or know of a better way to attempt this?

Thanks

Here is a PERL example, from one of my scripts:


$mtime = microtime();
$mtime = explode(' ', $mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
// your system commands / work here
$mtime = microtime();
$mtime = explode(" ", $mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
//
// do some more stuff
//
$to = "me@whereiam.com";
$subject = "My Subject";
$body = "Process executed in " .$totaltime. " seconds.";
$header = "From: me @ whereiwas . com]\r\n";
$header .= "Return-Path: me @ whereiwas . com\r\n";
$header .= "Reply-To: me @ whereiwas . com\r\n";
$success = mail($to, $subject, $body, $header);
//
// email addresses with spaces added

Hello, systrex:

Perhaps the `time` command may be of use.

Regards,
Alister

How about the bash/ksh env variable $SECONDS?

Here is some code to get into human readable form, just call duration_str with number of seconds eg:

START=$SECONDS
...My command to time....
duration_str $(($SECONDS-$START))
plural()
{
 # usage: plural <value> <word>
 [ $1 -eq 1 ] && echo $1 $2 || echo $1 ${2}s
}

duration_sub()
{
  # Input <duration> <A-div> <A-desc> <B-div> <B-desc>
  let DUR_A=$1/$2
  let DUR_B=$1-DUR_A*$2
  let DUR_B/=$4
  echo $(plural $DUR_A $3) $(plural $DUR_B $5)
}

duration_str()
{
 # Input param1 is duration in seconds
 # Outputs human readable string to stdout

 DUR=$1
 [ $DUR -le 60      ] && echo $(plural $DUR second) && return
 [ $DUR -le 3600   ] && duration_sub $DUR    60 minute    1 second && return
 [ $DUR -le 86400  ] && duration_sub $DUR  3600 hour     60 minute && return
 [ $DUR -le 604800 ] && duration_sub $DUR 86400 day    3600 hour   && return
 # Older than a week
 duration_sub $DUR 604800 week 86400 day
}