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