【发布时间】: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);”来实现要求命令。这确保了要测量的函数在输出文件中正确记录。