简体   繁体   中英

How to calculate total time of program after fork()

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <math.h>
#include <sys/time.h>
#include <stdlib.h>

void loopFunc(void)
{
  for (int i = 0; i < 10000; i++)
  {
    int temp = pow(i, 2);
  }
}
int main(int argc, char *argv[])
{

  struct timeval begin, end;
  gettimeofday(&begin, 0);

  if (fork() == 0)
  {
    loopFunc();
    printf("Child");
  }

  else
  {
    loopFunc();
    printf("Parent");
  }

  gettimeofday(&end, 0);
  long seconds = end.tv_sec - begin.tv_sec;
  long microseconds = end.tv_usec - begin.tv_usec;
  double elapsed = seconds + microseconds * 1e-6;
  printf("Time measured: %.3f seconds.\n", elapsed);
  return 0;
}

I have been given a task to calculate the real time of the program in which both child process and parent process is included. Now, I want to calculate the real time taken for the whole program but it is printing it two times because of fork() being called. How can I print the real time only one time? I can't find any way. Please help.

If you want to count the two processes separately, and then add the two times to display in only one process? That's not trivial, as the two processes are separate.

But if all you wait for the child process in the parent, then you can calculate the time of the child process simply by knowing when you start it and when it ends.

And since both processes will to basically the same work (call loopFunc ) then you don't need a check for that.

So in pseudo-code it could look something like this:

start_time = get_time();

int fork_result = fork();

loopFunc();

if (fork_result == 0)
{
    printf("Child finished\n");
    exit(EXIT_SUCCESS);  // Terminate the child process
}
// We can only come here in the parent process,
// the child process will never get here

parent_end_time = get_time();

printf("Parent finished\n");
wait();  // Wait for the child process to finish

child_end_time = get_time();

Now the parent process have the time it finished the loopFunc , as well as the time that the child process exited.

It can then do with those values as it pleases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM