#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <asm/unistd.h>
#include <linux/perf_event.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <stdint.h>
// Structure for perf_event_attr
struct perf_event_attr pe;
// need permsiion on perf_event_open
// to see value ->
// cat /proc/sys/kernel/perf_event_paranoid
//0: Allows access to all users to use perf_event_open for monitoring performance events.
//1: Allows access only to privileged users (typically root) to use perf_event_open.
//2: Disallows access to all users to use perf_event_open
//sudo sysctl kernel.perf_event_paranoid=<new_value>
// Function to initialize and read CPU cycle count
uint64_t read_cpu_cycles() {
// Initialize perf_event_attr structure
memset(&pe, 0, sizeof(struct perf_event_attr));
pe.type = PERF_TYPE_HARDWARE;
pe.config = PERF_COUNT_HW_CPU_CYCLES;
// Open the event
int fd = syscall(__NR_perf_event_open, &pe, 0, -1, -1, 0);
if (fd == -1) {
perror("Error opening leader %llx");
//exit(EXIT_FAILURE);
return 0;
}
// Read the counter
uint64_t count;
read(fd, &count, sizeof(uint64_t));
// Close the event
close(fd);
return count;
}
No comments:
Post a Comment