【问题标题】:calculate program execution time in c and linux在 c 和 linux 中计算程序执行时间
【发布时间】: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 之后。

标签: c linux


【解决方案1】:

您不能像以前那样使用时钟,因为在调用 exec 之后,您的代码被清除,因此您无法返回原始代码。您可以在父级中调用clock 之前的fork 和之后的wait,但它与子级消耗时间的近似值很差。

您有两个基本函数来跟踪子进程消耗的时间:

clock_t times(struct tms *tp);

这会给你调用者和孩子消耗的用户和系统时间。

int getrusage(int who, struct rusage *r_usage);

这可以让您选择跟踪谁(自己或孩子),并为您提供有关跟踪流程执行的更多详细信息。

等待孩子完成后,只需调用这两个之一。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    相关资源
    最近更新 更多