Displaying elapsed time...

I am trying to display the amount of time that it took for a command to run. I'm assuming that i have the correct code:

     ...
        else
          {
             printf("I am a child process and my pid is %d\n", getpid());
             cout<<"Parameters are: "<<endl;
              for (int j=0; j<i; j++)
                  cout<<doit[j]<<endl;
             cout<<"       EXECUTE CHILD"<<endl;
             initial=time(&initial);
             execve(doit[0], doit, NULL);
             final=time(&final);
             exit(0);
          }
       cout<<"     KILL CHILD AND RETURN TO PARENT"<<endl;
       printf("I am still the parent process and my pid is %d\n",
         getpid());
       //float elapsed=final-initial;
       printf("It took %u seconds to execute that command.\n",
          (final-initial));
...

and in my output, i keep getting "It took you 34 seconds to execute...." and I KNOW that isnt right. I have tried using %U, %S, %ld in place of %u and it either doesnt work or give me some off the wall answer.

I don't see a problem with the code you posted, but I'm guessing that you didn't declare "initial" and "final" to be ints. This works:

main()
{
      int one, two;
      one=time();
      sleep(3);
      two=time();
      printf("time = %d \n", (two-one));
      exit(0);
}

Also pick either "i=time();" or "time(&i)", it's silly to do both.

including <sys/time.h> with initial and final as type time_t, I cant just declare initial=time(). I have to have arguments so &initial serves the purpose. I'm still getting crazy output for the number of seconds though *shrug* Oh well..I'll just keep playing with it by putting final=time(&final); in various spots before the execve command.

I still suspect a mismatch with the printf format. Since you're using C++, why not try cout to print it out. I think:

cout << "Elapsed time " << (final-initial) << endl

will do it. But I'm not a C++ programmer.

I usually use clock() function, my code:

#include <stdio.h>
#include <time.h>

void main()
{
clock_t t1, t2;

t1 = clock\(\);
... // your action
t2 = clock\(\);

printf\("\\nFinished in %.2f seconds.\\n\\n", \(t2-t1\)*1.0/CLOCKS\_PER_SEC\);

}

t1 is the start time, t2 is the end time.

By using time() we are getting total elapsed time between the start and finish of the program. If we switch to clock(), we get the cpu time used. For some programs these will be nearly the same thing. But put a:
sleep(60);
in a program and now there is a big difference. For 60 seconds the process will be sleeping waiting a signal. Those 60 seconds will not show up with clock() since the cpu is not being used. They will show up with time().

And clock() also counts cpu time used by child processes that have exited and been reaped via wait(). In a multiprocessor environment the clock() time could exceed the time() time.