0

In same program we can calculate function execution time but How to calculate other program (c program) execution time in another program . i tried using execve() and clock() and system() but i didn't get program execution time .

example :

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<signal.h>
#include<time.h>

main(int argc, char *argv[])
{

    pid_t child;
    pid_t tpid;

    int   status;
    char *envp[] = {NULL};
    char *newargv[] = {argv[1],argv[2],argv[3],NULL};
    clock_t start, end;
    double time_taken;

    child = fork();

    if(child == 0)
    {


        printf("in child\n");
        start = clock();
        execve(argv[1], newargv,envp);
        end = clock();
        time_taken = ((double)(end - start))/CLOCKS_PER_SEC;
            printf("fun() took %f seconds to execute \n", time_taken);

        exit(1);
    }

        if(child != 0) 
    {
        /* This is run by the parent.  Wait for the child
        to terminate. */
//  end  = clock();
//  time_taken = ((double)(end - start))/CLOCKS_PER_SEC;
//  printf("fun() took %f seconds to execute \n", time_taken);
    printf(" in parent\n");
        do {
        pid_t tpid;
    tpid = wait(&status);
//          if(tpid != child) process_terminated(tpid);
        }while(tpid != child);

         //return status;
    }
}
2
  • You have a problem with your thinking: The exec family of function only returns if there's an error. If there is no error then they never returns. Commented Jan 9, 2017 at 8:05
  • You need to record the start time before calling fork. And the end time is after the wait in the parent. Commented Jan 9, 2017 at 8:16

1 Answer 1

1

You can't use clock the way you did, because after having call exec your code is cleared so you can't get back into the original code. You can call clock before fork and then after wait in the parent but its a bad approximation of the child consumed time.

You have two basic functions to track time consumed by child processes:

clock_t times(struct tms *tp);

that gives you user and system time consumed by caller and children.

int getrusage(int who, struct rusage *r_usage);

that can let you choose who to track (self or children) and gives you many more finer informations about execution of tracked processes.

Just call one of these two after having wait for child(ren) to finish.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.