在不阻止父进程的情况下测量子进程的时间

时间:2017-09-04 07:52:36

标签: fork cpu-time

我想测量子进程的执行时间。我可以使用时间功能 https://linux.die.net/man/3/times。但它需要使用wait()来阻止父进程。另一方面,我需要保持父进程并行运行以存储子进程生成的数据。孩子退出后,我想知道在执行子进程上花了多少CPU时间。如下所示:

int done = FALSE; 

struct timespec ts;
struct rusage ru;
struct timeval utime;
struct timeval stime;
int main(int argc, char* argv[]){   
        pid_t pid1, pid2; int status; 
        char *args[] = {"./wp"};
        struct rusage usage; 
        int i, j,n;
        signal(SIGCHLD,reaper); 
        pid1 = fork();
        if (pid1 == 0) {            // child
            printf("Its child %d\n",getpid());      
            printf("child %d: executing target program\n", getpid()); 
            execv(argv[1], argv+1);         
        }
       n = 0;
       while (n<20) {  //parent has to do some stuff in parallel
            printf("doing something...\n"); sleep(1); 
            if (done){ // child exited
                done = FALSE;
                pid_t pid2 = wait3(&status, 0, &usage); 
                printf("...child of %d done executing.\n",getpid()); 
                printf("exit code for %d is %d\n", pid2, status); 
                if (WIFEXITED(status)) 
                    printf("The exit status is %d\n", WEXITSTATUS(status));
                utime = usage.ru_utime;
                stime = usage.ru_stime;
                printf("RUSAGE :ru_utime => %lld [sec] : %lld [usec], :ru_stime => %lld [sec] : %lld [usec] \n",
               (int64_t)utime.tv_sec, (int64_t)utime.tv_usec,
               (int64_t)stime.tv_sec, (int64_t)stime.tv_usec);
            }
            n++;
        } 
       printf("got my SIGCHLD, cleaning up!\n"); 
       signal(SIGCHLD,SIG_DFL); 
       return 0;
    }

    void reaper(int sig) { 
       done=TRUE;  //  
    } 

0 个答案:

没有答案