在linux中查找CPU时间和进程的系统时间

时间:2016-10-13 08:59:12

标签: process resources

我有一个主程序可以创建两个孩子,每个孩子都会调用execlv。在程序结束时,如何计算父进程和两个进程的CPU时间和系统时间?

#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>



int main()
{


    pid_t pid1,pid2,wid;  // variable for parent and two children
  char *my_args[3];     // strign array for containing the arguments for executing sigShooter1
 // int aInt = 368;       //
  char str[15];     // strign to contain the pids of children when passing as command line arguments


   pid1 = fork();
   if (pid1 < 0)
    {
      fprintf(stderr, ": fork failed: %s\n", strerror(errno));
      exit(1);
    }

    if(pid1 == 0)
    {
      my_args[0] = "sigperf1";
      my_args[1] = "0";
      my_args[2] = NULL;
      execv("sigshooter1",my_args);
      fprintf(stderr,"sigshooter1 cannot be executed by first child...");
      exit(-1);
    }

    pid2 = fork();

    if(pid2 < 0)
    {
       fprintf(stderr, ": fork failed: %s\n", strerror(errno));
       exit(1);
    }

    if(pid2 == 0)
    {
      sprintf(str, "%d", pid1);
      my_args[0] = "sigperf1";
      my_args[1] = str;
      my_args[2] = NULL; 
     // printf("this is converted = %s\n",my_args[1]);
      //sleep(1);
      execv("sigshooter1",my_args);
      fprintf(stderr,"sigshooter1 cannot be executed by second child...");
      exit(-1);
    }


wid = wait(NULL);



}

1 个答案:

答案 0 :(得分:1)

你需要一个探查器。对于初学者,您可以运行perf stat ./a.out来获取所有三个进程的总CPU时间,并perf stat -i ./a.out来获取父进程的CPU时间。

如果您需要更详细的内容,请查看更为严肃的工具,例如valgrindgprof