You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于通过Perf_event_open系统调用获取PMU硬件性能计数器(CPU周期)的技术咨询

访问PMU获取CPU周期指标的C实现

我整理了一段针对Linux系统、用来访问硬件性能计数器(PMU)并重点统计CPU周期的C代码,它直接调用内核的perf_event接口来实现功能:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <string.h>
#include <sys/ioctl.h>
#include <linux/perf_event.h>
#include <linux/hw_breakpoint.h>
#include <asm/unistd.h>
#include <errno.h>
#include <stdint.h>
#include <inttypes.h>
#include <time.h>
// 注:原代码内容存在截断,若需要完整实现可补充后续统计、读取计数器的逻辑

实用注意事项

  • 这段代码依赖Linux内核的perf_event子系统,需要在支持PMU的CPU架构(比如x86、ARM)上运行
  • 编译时直接用GCC即可:gcc pmu_cycles.c -o pmu_cycles
  • 运行时通常需要root权限,或者调整系统参数降低perf_event的限制:sysctl kernel.perf_event_paranoid=0
  • 代码里用syscall直接调用perf_event_open是因为部分标准C库没有封装这个系统调用,属于Linux下的常规操作

内容的提问来源于stack exchange,提问作者SRT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:50:42