【发布时间】:2017-01-09 08:03:54
【问题描述】:
在同一个程序中,我们可以计算函数的执行时间,但是如何计算其他程序(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;
}
}
【问题讨论】:
-
你的想法有问题:
exec系列函数只有在出现错误时才会返回。如果没有错误,则它们永远不会返回。 -
您需要记录开始时间之前调用
fork。结束时间在父级中的wait之后。