我需要能够在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'时它也会获得性能统计信息。有人可以告诉我如何在程序中正确捕获所需的统计数据吗?。
感谢。
答案 0 :(得分:2)
实现您尝试做的事情的正确方法是使用perf_events API(或其他此类API,如PAPI)。这样,您就可以在代码中分析您感兴趣的部分。
您尝试使用的解决方案(在代码中调用perf二进制文件)是一个丑陋的黑客攻击。
答案 1 :(得分:2)
查看a = dict()
a['trees'] = dict()
a['trees']['oak'] = 453
a['trees']['pine'] = 12
a['trees']['chestnut'] = 65
for b in a:
if a.get("trees"):
print a.items()
他们最后也有示例代码。
http://web.eece.maine.edu/~vweaver/projects/perf_events/perf_event_open.html
答案 2 :(得分:1)
#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