土法炼钢兴趣小组的算法知识备份

【操作系统百科】perf 子系统

文章导航

分类入口
os
标签入口
#perf#pmu#perf-event#processor-trace#sampling

目录

perf statperf recordperf top——这些命令背后是内核的 perf_event 子系统,一个统一的性能事件框架。

一、先看图

flowchart TD
    USER[perf 工具] -->|perf_event_open| KERNEL[perf_event 子系统]
    KERNEL --> HW[硬件 PMU<br/>cycles, cache-misses]
    KERNEL --> SW[软件事件<br/>context-switches, page-faults]
    KERNEL --> TP[Tracepoints<br/>sched, block, net]
    KERNEL --> RB[Ring Buffer<br/>per-CPU mmap]
    RB --> USER

    classDef hw fill:#388bfd22,stroke:#388bfd,color:#adbac7;
    classDef sw fill:#3fb95022,stroke:#3fb950,color:#adbac7;
    class HW hw
    class SW,TP sw
    class USER,KERNEL,RB hw

二、perf_event_open

int fd = perf_event_open(&attr, pid, cpu, group_fd, flags);

核心系统调用 → 创建性能事件 → 返回 fd。

attr 指定事件类型、采样周期、输出格式。

三、事件类型

3.1 硬件事件

perf stat -e cycles,instructions,cache-misses ./my_app

通过 PMU(Performance Monitoring Unit)硬件计数器。

3.2 软件事件

perf stat -e context-switches,page-faults ./my_app

内核在关键路径上计数。

3.3 Tracepoints

perf stat -e sched:sched_switch ./my_app
perf record -e block:block_rq_issue -a sleep 5

四、Sampling vs Counting

模式 用途 开销
counting perf stat — 精确计数 极低
sampling perf record — 每 N 事件采样一次 低-中

采样:PMU 每 N 个 cycles 触发 NMI → 记录 IP(instruction pointer)→ 事后分析热点。

五、Ring Buffer

void *mmap_addr = mmap(NULL, size, PROT_READ, MAP_SHARED, perf_fd, 0);

perf 通过 mmap 共享 ring buffer → 内核写、用户态读 → 零拷贝。

六、perf record / report

perf record -g -F 99 ./my_app       # 采样 + 调用栈
perf report                           # 交互式分析
perf annotate                         # 源码级热点

6.1 调用栈

perf record --call-graph dwarf ./my_app   # DWARF unwind
perf record --call-graph fp ./my_app      # frame pointer
perf record --call-graph lbr ./my_app     # Last Branch Record

七、Processor Trace(Intel PT)

perf record -e intel_pt// ./my_app
perf script --itrace=i0ns

硬件记录完整的指令流 → 精确重放执行路径 → overhead 低于采样。

八、cgroup perf

perf stat -e cycles -G my_cgroup ./my_app

限定只统计特定 cgroup 内的事件 → 容器级性能分析。

九、观察

perf list                     # 可用事件
perf top                      # 实时热点
perf stat -d ./my_app         # 详细统计
perf bench sched all          # 内置 benchmark

# 火焰图
perf record -g -F 99 -a sleep 10
perf script | stackcollapse-perf.pl | flamegraph.pl > flame.svg

十、小结


参考文献

工具


上一篇ftrace 下一篇eBPF 核心

同主题继续阅读

把当前热点继续串成多页阅读,而不是停在单篇消费。

2026-04-27 · os

【操作系统百科】内存回收

Linux 内存回收是 VM 最复杂的子系统之一。本文讲 active/inactive LRU、kswapd 与 direct reclaim、watermark 三线、swappiness 的真实含义、MGLRU 改造、memcg 回收与 PSI。

2026-04-28 · os

【操作系统百科】交换

swap 还值得开吗?本文讲 swap area 基础、swap cache、zram 压缩内存、zswap 前端压缩池、swappiness 的真实含义、容器里的 swap 策略,以及为什么现代 Android 全靠 zram 不靠磁盘。

2026-05-03 · os

【操作系统百科】Slab/SLUB 分配器

buddy 只管页粒度(4K+),内核大多数对象只有几十到几百字节。slab/SLUB 在 buddy 之上做对象级缓存。本文讲 slab 历史、SLUB 接手、SLOB 退场、kmem_cache、per-CPU cache、KASAN 集成。

2026-05-07 · os

【操作系统百科】用户态分配器

glibc malloc、tcmalloc、jemalloc、mimalloc 各有哲学。本文讲 arena、thread cache、size class、madvise 返还策略、碎片与 RSS 膨胀、如何根据负载选分配器。


By .