Reputation: 585
I need to be able execute 'perf stats' within a C program to gather real time execution statistics of a particular function that is executed inside a loop. A shell script ('perfExecution.sh') is created which includes,
pid=$(pgrep programName)
perf stat -e cycles,instructions,cache-misses:uk -p $pid 2>perf_stat.out 1>temp2.out
Here the 'programeName' is the name of my C programme and the 'perfExecution.sh' is executed as a child process within the main C program before the functions that should be analyzed are called.
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.
*/
`
The output file always returns blank, even though the it gets the performance statistics when the 'perfExecution.sh' is manually executed in another terminal. Could someone please let me know how to correctly capture the required statistics within the program it self?.
Thanks.
Upvotes: 2
Views: 1906
Reputation: 3244
Look at perf_event_open()
They also have sample code at the end.
http://web.eece.maine.edu/~vweaver/projects/perf_events/perf_event_open.html
Upvotes: 2
Reputation: 1293
The proper way to achieve what you're trying to do would be to use the perf_events API (or another such API, like PAPI). This would allow you from within your code to profile the section you're interested in.
The solution you're trying to use (calling the perf binary within your code) is an ugly hack.
Upvotes: 2
Reputation: 611
#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;
}
Can read more here: http://www.unix.com/programming/216190-putting-bash-script-c-program.html
To Capture the output type man popen
on command line and read about popen
Upvotes: 1