gpt4 book ai didi

c - 可能滥用 perf_event_open 系统调用

转载 作者:太空宇宙 更新时间:2023-11-04 10:17:30 24 4
gpt4 key购买 nike

我正在试验 PERF_EVENTS,这是 Linux 内核提供的性能事件接口(interface)。我通过 perf_event_open 系统调用成功获取了性能参数(cpu 周期,...)。

long
perf_event_open(struct perf_event_attr *hw_event, pid_t pid,
int cpu, int group_fd, unsigned long flags)
{
int ret;

ret = syscall(__NR_perf_event_open, hw_event, pid, cpu,
group_fd, flags);
return ret;
}

int
main(int argc, char **argv)
{
struct perf_event_attr pe;
long long count;
int fd;

memset(&pe, 0, sizeof(struct perf_event_attr));
pe.type = PERF_TYPE_HARDWARE;
pe.size = sizeof(struct perf_event_attr);
pe.config = PERF_COUNT_HW_CPU_CYCLES;
pe.disabled = 1;
pe.exclude_idle = 1;
pe.exclude_kernel = 1;
pe.exclude_callchain_kernel = 1;

fd = perf_event_open(&pe, 0, -1, -1, 0);
if (fd == -1) {
fprintf(stderr, "Error opening leader %llx\n", pe.config);
exit(EXIT_FAILURE);
}

ioctl(fd, PERF_EVENT_IOC_RESET, 0);
ioctl(fd, PERF_EVENT_IOC_ENABLE, 0);

printf("Measuring instruction count for this printf\n");

ioctl(fd, PERF_EVENT_IOC_DISABLE, 0);
read(fd, &count, sizeof(long long));

printf("%lld \n", count);

return 0;
}

但是,我并不完全理解 perf_event_open 的用法。我盲目地传递 -1 作为第四个参数。我不知道何时对事件进行分组,何时将它们分开,其中一个应该是组的“领导者”。

下面是第4个参数的说明:

The group_fd argument allows event groups to be created. An event group has one event which is the group leader. The leader is created first, with group_fd = -1. The rest of the group members are created with subsequent perf_event_open() calls with group_fd being set to the fd of the group leader. (A single event on its own is created with group_fd = -1 and is considered to be a group with only 1 member.) An event group is scheduled onto the CPU as a unit: it will only be put onto the CPU if all of the events in the group can be put onto the CPU. This means that the values of the member events can be meaningfully compared, added, divided (to get ratios), etc., with each other, since they have counted events for the same set of executed instructions.

那么有人可以阐明 4 号(如果可能的话,它与 5 号的关系)吗?什么是正确的做事方式?还有一个例子会让事情变得更好。

最佳答案

我不确定这些标志,但我可以给这个组一些颜色,虽然我不知道这是否充分回答了你的问题,而不仅仅是改写你引用的文档。

CPU 硬件非常有限^,因此必须共享对计数器的访问。因此,当操作系统不时决定谁可以使用底层物理资源时,您的资源可能会被取消映射和重新映射。

某些测量只有在同时测量两个计数器时才有意义:例如采用的分支数与预测错误的分支数。

为了确保您的两个计数器由操作系统一起安排在 CPU 上和关闭 CPU,而不是独立的,您需要组成一个组。其中一个应该是领导者,然后另一个将使用第一个计数器的 fd 作为领导者。

然后您就知道您读取的任何计数都来自两个计数器同时启用和运行的时间。

^ 除了诸如“循环退役”之类的一些常见问题外,大多数英特尔 CPU 一次仅支持从数百个调色板中测量四种事件类型。

关于c - 可能滥用 perf_event_open 系统调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45421150/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com