time function

Hi,

   I would like to display the exact time taken to complete running a particular tool or function or program to user

   I don't know the exact time functions in unix, please help me

 thanks in advance
Example:
     
    $test.ksh

    output should be
    The time taken to execute the test.ksh file is 00.30.00 seconds
time test.ksh

hi anbu,

    the code 
 time test.ksh
    is working when i am executing my file from command line, but i want to include the code inside my code, how can i achieve that one.

create a string that forms the command as run in command line,

char command[50];
sprintf(command, "time %s", commandtorun);

and you have to run this " command " with " popen "
which would execute and you have would have execution time in the pipe, which you need to parse it and display! :slight_smile:

Just a pointer !
If you need more explanations, shoot ! :slight_smile:

hi matrixmadhan,

 thanks for your reply,

 the code
     char command[50];
sprintf(command, "time %s", commandtorun);
I think code which u have given will not work in ksh program. can u send me the code relavent to ksh

thanks,
hsekol

do you want to experiment that with the shell - command line or in a code ?

am not clear about that!

If that is in a code, use what I had specified
if not, to be used in a shell, you can use

time
times

Else,
post your specific requirement! :slight_smile:

Hi matrixmadhan,

 thanks for your quick reply,

 my requirement is 

 Example:
    echo "Enter i value"
      read i
      n=0
      while [ $n -eq $i ]
      do
          echo $i
          i=`expr $i + 1`
      done
 let's assume that for the first time, i have given 50 as i value, so while loop will execute for 50 times and atlast the program have to display the actual time taken to complete program to execute \(this one i want for performance\) this program i have written in ksh

I think u got my requirement, i have write the time function in side the code only

and this,
:slight_smile:

#! /bin/zsh

i=0

read n < /dev/tty

start=`date '+%s'`
while [ $i -le $n ]
do
  i=$(($i + 1))
done

echo "diff is $((`date '+%s'` - $start)) second(s)"

exit 0

thanks madan, the code which u have given is working...thanxs a lot

$ cat /tmp/time.ksh
#!/bin/ksh
let i=0
while [[ i -le 1000 ]] ; do
echo $i
((i=i+1))
done
echo "This has taken $SECONDS to complete"

SECONDS holds the number seconds since the shell was invocated.But this may not provide microseconds resolutions.

Thanks
Nagaraj G

I dont think you could block the amount of time taken to execute within blocks within a code,

as posted by the OP,

read operation might take a subtle amount of time to pass on the value for the for loop where the effective time taken is calculated.

:slight_smile: