Debian Codegraph @

benchmarks/linux-perf-events.h

raw
1 #pragma once
2 #ifdef __linux__
3
4 #include <asm/unistd.h> // for __NR_perf_event_open
5 #include <linux/perf_event.h> // for perf event constants
6 #include <sys/ioctl.h> // for ioctl
7 #include <unistd.h> // for syscall
8
9 #include <cerrno> // for errno
10 #include <cstring> // for memset
11 #include <stdexcept>
12
13 #include <iostream>
14 #include <vector>
15
16 template <int TYPE = PERF_TYPE_HARDWARE> class LinuxEvents {
17 int fd;
18 bool working;
19 perf_event_attr attribs{};
20 size_t num_events{};
21 std::vector<uint64_t> temp_result_vec{};
22 std::vector<uint64_t> ids{};
23
24 public:
25 explicit LinuxEvents(std::vector<int> config_vec) : fd(0), working(true) {
26 memset(&attribs, 0, sizeof(attribs));
27 attribs.type = TYPE;
28 attribs.size = sizeof(attribs);
29 attribs.disabled = 1;
30 attribs.exclude_kernel = 1;
31 attribs.exclude_hv = 1;
32
33 attribs.sample_period = 0;
34 attribs.read_format = PERF_FORMAT_GROUP | PERF_FORMAT_ID;
35 const int pid = 0; // the current process
36 const int cpu = -1; // all CPUs
37 const unsigned long flags = 0;
38
39 int group = -1; // no group
40 num_events = config_vec.size();
41 ids.resize(config_vec.size());
42 uint32_t i = 0;
43 for (auto config : config_vec) {
44 attribs.config = config;
45 int _fd = static_cast<int>(
46 syscall(__NR_perf_event_open, &attribs, pid, cpu, group, flags));
47 if (_fd == -1) {
48 report_error("perf_event_open");
49 }
50 ioctl(_fd, PERF_EVENT_IOC_ID, &ids[i++]);
51 if (group == -1) {
52 group = _fd;
53 fd = _fd;
54 }
55 }
56
57 temp_result_vec.resize(num_events * 2 + 1);
58 }
59
60 ~LinuxEvents() {
61 if (fd != -1) {
62 close(fd);
63 }
64 }
65
66 inline void start() {
67 if (fd != -1) {
68 if (ioctl(fd, PERF_EVENT_IOC_RESET, PERF_IOC_FLAG_GROUP) == -1) {
69 report_error("ioctl(PERF_EVENT_IOC_RESET)");
70 }
71
72 if (ioctl(fd, PERF_EVENT_IOC_ENABLE, PERF_IOC_FLAG_GROUP) == -1) {
73 report_error("ioctl(PERF_EVENT_IOC_ENABLE)");
74 }
75 }
76 }
77
78 inline void end(std::vector<unsigned long long> &results) {
79 if (fd != -1) {
80 if (ioctl(fd, PERF_EVENT_IOC_DISABLE, PERF_IOC_FLAG_GROUP) == -1) {
81 report_error("ioctl(PERF_EVENT_IOC_DISABLE)");
82 }
83
84 if (read(fd, temp_result_vec.data(), temp_result_vec.size() * 8) == -1) {
85 report_error("read");
86 }
87 }
88 // our actual results are in slots 1,3,5, ... of this structure
89 for (uint32_t i = 1; i < temp_result_vec.size(); i += 2) {
90 results[i / 2] = temp_result_vec[i];
91 }
92 for (uint32_t i = 2; i < temp_result_vec.size(); i += 2) {
93 if (ids[i / 2 - 1] != temp_result_vec[i]) {
94 report_error("event mismatch");
95 }
96 }
97 }
98
99 bool is_working() { return working; }
100
101 private:
102 void report_error(const std::string &) { working = false; }
103 };
104 #endif