【发布时间】:2019-08-29 11:56:50
【问题描述】:
我正在为我编写的软件设置分析,但我无法使用 perf_event_open 获得上下文切换计数。
为了测试这个问题,我也尝试使用perf_event_openman_page 上提供的示例代码。使用sched_yield 并使用任务集在同一内核上运行并行进程来强制上下文切换。使用perf_event_open() 进行上下文切换的计数仍为 0。(使用 perf stat 时,我得到非零数字:大循环为数千)。我也尝试过执行文件读取/使用 mmap 来强制页面错误。
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/ioctl.h>
#include <linux/perf_event.h>
#include <asm/unistd.h>
#include <iostream>
#include <string.h>
#include <sys/mman.h>
using namespace std;
int buf_size_shift = 8;
static unsigned perf_mmap_size(int buf_size_shift)
{
return ((1U << buf_size_shift) + 1) * sysconf(_SC_PAGESIZE);
}
static 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_SOFTWARE;
//pe.sample_type = PERF_SAMPLE_CALLCHAIN; /* this is what allows you to obtain callchains */
pe.size = sizeof(struct perf_event_attr);
pe.config = PERF_COUNT_SW_CONTEXT_SWITCHES;
pe.disabled = 1;
pe.exclude_kernel = 1;
pe.sample_period = 1000;
pe.exclude_hv = 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);
}
/* associate a buffer with the file */
struct perf_event_mmap_page *mpage;
mpage = (perf_event_mmap_page*) mmap(NULL, perf_mmap_size(buf_size_shift),
PROT_READ|PROT_WRITE, MAP_SHARED,
fd, 0);
if (mpage == (struct perf_event_mmap_page *)-1L) {
close(fd);
return -1;
}
ioctl(fd, PERF_EVENT_IOC_RESET, 0);
ioctl(fd, PERF_EVENT_IOC_ENABLE, 0);
printf("Measuring instruction count for this printf\n");
long long sum = 0;
for (long long i = 0; i < 10000000000; i++) {
sum += i;
if (i%1000000 == 0)
cout << i << " : " << sum << endl;
}
ioctl(fd, PERF_EVENT_IOC_DISABLE, 0);
read(fd, &count, sizeof(long long));
printf("Used %lld cs\n", count);
close(fd);
}
type = PERF_COUNT_SOFTWARE 和 config = PERF_COUNT_SW_CONTEXT_SWITCHES 的代码即使在强制上下文切换的情况下也会在计数中输出 0。在其他指标起作用的情况下。
在使用 mmap 环形缓冲区时,我看到 PERF_RECORD_SWITCH 记录在读取它,而根据我的理解是正在记录上下文切换事件。
任何关于性能计数和环形缓冲区中的数据如何相关的信息也很感激。
【问题讨论】:
标签: c++ profiling perf context-switch