c - 在 C 程序中执行 'perf'

标签 c ubuntu fork perf

我需要能够在 C 程序中执行“perf stats”,以收集循环内执行的特定函数的实时执行统计信息。创建一个 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”时获取性能统计信息。有人可以让我知道如何在程序本身中正确捕获所需的统计信息吗?

谢谢。

最佳答案

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

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

关于c - 在 C 程序中执行 'perf',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31794827/

相关文章:

c - 当我尝试从 C 中 unsafe_load 一个指针时,Julia 得到了错误的值

c - 是否有不从第一个字节开始的 sscanf() 版本?

python - 调试(过早?)OOM-killer 输出

c - 在GDB中使用命令 'x/20x $esp',栈是怎么工作的?

c - POSIX C 中 fork() 的重量更轻的替代品?

c - fork 进程的执行顺序

c - fork()命令多少个进程

c - Cudamalloc 的神秘段错误

c - 在C中递增指向多维数组的指针

node.js - 无法在适用于 Linux 的 Windows 子系统(ubuntu)上运行 react 服务器