#include <unistd.h> #include <stdio.h> #include <signal.h> int main() { int pid= getpid(); int cpid = fork(); if( cpid == 0) { // child process . Run your perf stat char buf[100]; sprintf(buf, "perf stat -e cache-misses -p %d",pid); execl("/bin/sh", "sh", "-c", buf, NULL); } else { // set the child the leader of its process group setpgid(cpid, 0); // ////////////////////////////////////////////// // // part of program you wanted to perf stat // sleep(3); // //////////////////////////////////////////////// unsigned long long sum = 0; int* values = new int[64000000]; for (int i = 0; i < 64000000; i++) { values[i] = i; } for (int i = 0; i < 64000000; i++) { sum += values[i]; } for (int i = 0; i < 64000000; i++) { values[i] = sum; } printf("%llu\n", sum); //////////////////////////////////////////////////////////////// // stop perf stat by killing child process and all its descendants(sh, perf stat etc ) kill(-cpid, SIGINT); //////////////////////////////////////////////////////////////////// // unsigned long long sum = 0; // for (int i = 0; i < 64000000; i++) { // sum += values[i]; // } // printf("%llu\n", sum); // rest of the program // sleep(2); } }