Files
sakurac/tools/profile/count.c
T
2026-11-19 04:54:17 -06:00

79 lines
2.7 KiB
C

// Runs a program pinned to one processor and counts its work with the processor's
// own counters, which need no kernel profiling support beyond `perf_event_open`.
//
// cc -O2 -o count count.c
// count CPU PROGRAM ARGS...
//
// Prints to the standard error, on one line: the wall time in seconds, the peak
// resident memory in KB, the instructions and the cycles the program and its threads
// ran outside the kernel, and its exit status. A CPU below 0 doesn't pin it. The
// program's output is discarded.
//
// The counters are the performance cores' (`cpu_core`), as this processor's efficiency
// cores count no cycles, so pin to a performance core. They need
// `/proc/sys/kernel/perf_event_paranoid` at 2 or less.
#define _GNU_SOURCE
#include <fcntl.h>
#include <linux/perf_event.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
static int open_counter(pid_t pid, unsigned long long type, unsigned long long config) {
struct perf_event_attr a;
memset(&a, 0, sizeof a);
a.size = sizeof a;
a.type = PERF_TYPE_HARDWARE;
a.config = (type << 32) | config;
a.disabled = 1;
a.enable_on_exec = 1;
a.inherit = 1;
a.exclude_kernel = 1;
a.exclude_hv = 1;
return (int)syscall(SYS_perf_event_open, &a, pid, -1, -1, 0);
}
int main(int argc, char **argv) {
int cpu = atoi(argv[1]);
FILE *f = fopen("/sys/bus/event_source/devices/cpu_core/type", "r");
unsigned long long type = 0;
if (f) { if (fscanf(f, "%llu", &type) != 1) type = 0; fclose(f); }
int go[2];
if (pipe(go)) return 1;
struct timespec t0, t1;
pid_t pid = fork();
if (pid == 0) {
if (cpu >= 0) {
cpu_set_t set; CPU_ZERO(&set); CPU_SET(cpu, &set);
sched_setaffinity(0, sizeof set, &set);
}
close(go[1]);
char c; if (read(go[0], &c, 1) != 1) _exit(127);
int null = open("/dev/null", O_WRONLY);
dup2(null, 1);
execvp(argv[2], argv + 2);
_exit(127);
}
close(go[0]);
int ins = open_counter(pid, type, PERF_COUNT_HW_INSTRUCTIONS);
int cyc = open_counter(pid, type, PERF_COUNT_HW_CPU_CYCLES);
clock_gettime(CLOCK_MONOTONIC, &t0);
if (write(go[1], "x", 1) != 1) return 1;
int status; struct rusage ru;
wait4(pid, &status, 0, &ru);
clock_gettime(CLOCK_MONOTONIC, &t1);
long long ni = -1, nc = -1;
if (ins >= 0 && read(ins, &ni, sizeof ni) != sizeof ni) ni = -1;
if (cyc >= 0 && read(cyc, &nc, sizeof nc) != sizeof nc) nc = -1;
double wall = (t1.tv_sec - t0.tv_sec) + (t1.tv_nsec - t0.tv_nsec) / 1e9;
fprintf(stderr, "%.4f %ld %lld %lld %d\n", wall, ru.ru_maxrss, ni, nc,
WIFEXITED(status) ? WEXITSTATUS(status) : -1);
return 0;
}