【问题标题】:executing 'perf' within a C program在 C 程序中执行“perf”
【发布时间】:2015-08-07 19:12:09
【问题描述】:

我需要能够在 C 程序中执行“性能统计”,以收集在循环中执行的特定函数的实时执行统计信息。创建了一个 shell 脚本('perfExecution.sh'),其中包括,

pid=$(pgrep programName)
perf stat -e cycles,instructions,cache-misses:uk -p $pid 2>perf_stat.out 1>temp2.out

这里的“programeName”是我的 C 程序的名称,“perfExecution.sh”在调用应该分析的函数之前作为主 C 程序中的子进程执行。

pid_t childPID = fork();
char perfBuf[200];
int pid = getpid();
if ( childPID == -1 )
{
   printf( "failed to fork child\n" );
   _exit( 1 );
}
else if ( childPID == 0 )
{
   std::cout << "started stat collection for: " << pid << "\n";

   sprintf(perfBuf, "/home/user/Documents/Project/perfExecution.sh");
   system(perfBuf);
}
/*
  Functions to be measured.
*/
kill( childPID, SIGKILL );
/*
    Collect the statistics generated from perf.
*/
 `

输出文件总是返回空白,即使在另一个终端中手动执行“perfExecution.sh”时它会获得性能统计信息。有人可以让我知道如何在它自己的程序中正确捕获所需的统计信息吗?。

谢谢。

【问题讨论】:

  • 你确定这是 C 吗?这在我看来就像 C++。
  • @TrippKinetics 确实 std::cout ... 是 C++,但问题全在于 C。
  • 另一种解决方案是使用fork()exec() 的变体
  • @userDtrm 为什么不使用“perf stat”的“-o file”选项将命令的输出写入文件?为什么你绝对想从你的程序内部运行 perf 来分析它的执行?在什么情况下运行“perf stat -o outputfile.stats programName”不合适?
  • 感谢大家的建议。我能够通过使用命令“killall -INT perf”而不是“kill(childPID, SIGKILL);”来实现要求命令。这确保了要测量的函数在输出文件中正确记录。

标签: c ubuntu fork perf


【解决方案1】:

实现您想要做的事情的正确方法是使用 perf_events API(或其他此类 API,如 PAPI)。这将允许您从代码中分析您感兴趣的部分。

您尝试使用的解决方案(在代码中调用 perf 二进制文件)是一个丑陋的 hack。

【讨论】:

    【解决方案2】:

    perf_event_open()

    他们最后也有示例代码。

    http://web.eece.maine.edu/~vweaver/projects/perf_events/perf_event_open.html

    【讨论】:

    • 感谢您的意见。这似乎符合我的目的。
    【解决方案3】:
    #include <stdio.h>
    #include <stdlib.h>
    
    /* put script code here or in a header file of your choice */
    #define SCRIPT "\
    for ((j=0 ; j < 5 ; j++))\n\
    do\n\
    echo \"Count: $i\"\n\
    done\n\
    "
    
    int main(void)
    {
      system(SCRIPT);
      return 0;
    }
    

    可以在这里阅读更多内容:http://www.unix.com/programming/216190-putting-bash-script-c-program.html

    在命令行捕获输出类型man popen并阅读popen

    【讨论】:

    • 谢谢。是的,通用脚本确实以这种方式工作。我发现它不适用于我在问题中提到的“perf stat”脚本。你知道为什么吗?。
    • @Kaleb 很抱歉,但我不明白上面的代码在什么方面有助于解决最初的问题。
    猜你喜欢
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    • 1970-01-01
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多