在同一个程序中我们可以计算函数执行时间但是如何计算另一个程序中的其他程序(c程序)执行时间。我尝试使用execve()和clock()和system(),但我没有得到 程序执行时间。
示例:
#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;
}
}
答案 0 :(得分:1)
你不能像你那样使用时钟,因为在调用exec
后你的代码被清除,所以你无法回到原始代码。您可以在clock
之前拨打fork
,然后在父级wait
之后拨打电话,但这与儿童消耗的时间差不大。
您有两个基本功能来跟踪子进程消耗的时间:
clock_t times(struct tms *tp);
为您提供呼叫者和子女消耗的用户和系统时间。
int getrusage(int who, struct rusage *r_usage);
可以让您选择跟踪的人(自己或孩子),并为您提供有关跟踪流程执行的更多更精细的信息。
在等待孩子完成后,只需拨打其中一个。