我需要能够在 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/