5#include <linux/perf_event.h>
16template <
int TYPE = PERF_TYPE_HARDWARE>
20 perf_event_attr attribs{};
22 std::vector<uint64_t> temp_result_vec{};
23 std::vector<uint64_t> ids{};
26 explicit LinuxEvents(std::vector<int> config_vec) : fd(0), working(true) {
27 memset(&attribs, 0,
sizeof(attribs));
29 attribs.size =
sizeof(attribs);
31 attribs.exclude_kernel = 1;
32 attribs.exclude_hv = 1;
34 attribs.sample_period = 0;
35 attribs.read_format = PERF_FORMAT_GROUP | PERF_FORMAT_ID;
38 const unsigned long flags = 0;
41 num_events = config_vec.size();
42 ids.resize(config_vec.size());
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));
49 report_error(
"perf_event_open");
51 ioctl(_fd, PERF_EVENT_IOC_ID, &ids[i++]);
58 temp_result_vec.resize(num_events * 2 + 1);
69 if (ioctl(fd, PERF_EVENT_IOC_RESET, PERF_IOC_FLAG_GROUP) == -1) {
70 report_error(
"ioctl(PERF_EVENT_IOC_RESET)");
73 if (ioctl(fd, PERF_EVENT_IOC_ENABLE, PERF_IOC_FLAG_GROUP) == -1) {
74 report_error(
"ioctl(PERF_EVENT_IOC_ENABLE)");
79 inline void end(std::vector<unsigned long long> &results) {
81 if (ioctl(fd, PERF_EVENT_IOC_DISABLE, PERF_IOC_FLAG_GROUP) == -1) {
82 report_error(
"ioctl(PERF_EVENT_IOC_DISABLE)");
85 if (read(fd, temp_result_vec.data(), temp_result_vec.size() * 8) == -1) {
90 for (uint32_t i = 1; i < temp_result_vec.size(); i += 2) {
91 results[i / 2] = temp_result_vec[i];
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");
100 bool is_working() {
return working; }
103 void report_error(
const std::string &) { working =
false; }