30 秒面试回答
perf 可以汇总硬件或软件事件,也可以采样执行位置和调用栈。火焰图把相同调用路径聚合起来,便于查看样本集中在哪里;常见 CPU 图的宽度代表样本权重,横轴不表示执行顺序。看到热点后,还要核对事件、栈质量、采样覆盖与绝对耗时,再通过受控改动验证它是否限制业务吞吐或延迟。睡眠等待需要额外的 off-CPU 证据。
核心概念
计数回答“这一段发生了多少”,采样回答“抽到的事件落在什么位置”。perf stat 通常读取汇总结果;perf record 保存采样数据,perf report 和 perf script 再做展示或导出。一个进程的指令总数不会自动告诉我们每条调用路径占了多少。perf-stat(1)、perf-record(1)
| 观察方式 | 可以支持的判断 | 需要补充的边界 |
|---|---|---|
| task-clock 计数 | 选定任务运行的 CPU 时间量级 | 不是请求从到达到完成的经过时间 |
| cycles 或 cpu-clock 栈采样 | 指定事件下的执行路径分布 | 事件不同,权重与解释也不同 |
| 调度切换与持续时间 | 哪些栈对应阻塞或等待区间 | 需区分睡眠与已就绪但尚未运行 |
| 请求时间戳 | 排队和各处理段的延迟 | 要保留到达过程及测量边界 |
on-CPU 表示线程正在 CPU 上运行;off-CPU 包括不在运行的时间。阻塞锁通常使线程睡眠,自旋锁仍消耗 CPU。采样 CPU 栈不能完整解释睡眠等待时长。阻塞栈、唤醒事件与调度延迟还可能分别指向等待者和造成等待的线程。Off-CPU Analysis
原理深入
采样记录包含指令地址,启用调用栈采集后还包含调用链或展开所需数据。把每条栈折叠为 入口;调用者;叶函数 权重,相同路径的权重相加,便得到火焰图输入。具体导出工具可能按样本条数或其他权重聚合,比较两张图之前必须确认这一点。FlameGraph 工作流
一个矩形的宽度包括经由它进入子调用的权重。顶部没有子块覆盖的部分对应这条路径上直接落在该函数的样本;同名函数若出现在不同调用路径,可能出现多个块。普通火焰图按调用关系聚合与排列,左右相邻不意味着先后执行,默认配色也不能用来读取耗时高低。需要时间顺序时应使用保留时间维度的视图。CPU Flame Graphs
perf report 的 self 与 children 分别帮助查看自身和包含子调用的归因。一个入口函数 children 很大,可能只是绝大多数工作都由它发起。需要下钻到实际路径,再考虑减少调用、批量处理或改变实现。父子占比有重叠,不能沿栈相加得到新的总耗时。perf-report(1)
采样比例还依赖分母。某函数从 40% 变成 20%,可能是它变快,也可能是别处新增开销。若要验证“减少分配改善解析吞吐”,同时检查同等消息量的分配次数、CPU 时间和完成速率,保持消息分布与线程放置一致。图上的归因提供待检验的原因,优化前后的对照才检验这个原因是否成立。
数据结构/系统内部实现
perf_event_open 用 perf_event_attr 指定事件和范围,返回 fd。计数模式通过 read 取值;采样模式把记录写入 mmap ring buffer,由消费者读取。环形缓冲区装不下记录时可能丢样,内核文档说明了缓冲区的生产与消费协议。采样频率、记录大小与读取速度都会影响这条路径。Perf ring buffer
本例只打开当前线程的 PERF_COUNT_SW_TASK_CLOCK,pid=0, cpu=-1,不继承其他线程,请求 exclude_kernel/hv 过滤,初始禁用并设置 close-on-exec。预热与功能自测在 enable 之前完成。计数区间仍包含 enable 返回、finish 控制路径及每轮 checksum 比较,因此不会把结果标成某个函数的纯执行时间。过滤属性也不能直接保证软件时钟是严格的用户态时间:Linux v6.8 的 task_clock_event_update 累加上下文时钟差值,没有在这个更新路径按用户态与内核态拆分。本机内核版本不同,本章仅将输出解释为该软件事件的计数,不把它换算成纯用户态工作耗时。Linux v6.8 task-clock 实现
计数器复用时保留 value、time_enabled 和 time_running。当 running 非零,可用 value × enabled / running 估计完整区间计数;先转成浮点等合适类型,避免整数乘法溢出。这个估计假设实际运行片段具有代表性,阶段负载可能使误差很大。running 为零时不做除法。事件组能让成员覆盖同一组已计数执行,但组太大或事件约束冲突也可能无法调度。perf_event_open(2)
函数名解析和栈展开需要分别检查。符号文件把地址关联到函数或源码;frame pointer 展开沿帧链回溯,DWARF 模式则保存用户栈片段并使用展开信息。栈片段过短、库缺少相应信息、工具未包含展开支持,都可能得到不完整链。内联函数没有独立的物理调用帧,工具可以利用调试信息恢复部分内联位置;尾调用优化也会改变可见调用关系。perf-record(1)
-fno-omit-frame-pointer 有助于 FP 方式,但 GCC 文档明确它不保证所有函数都保留 frame pointer。给主程序加选项也不会重新编译已有共享库。示例用 GNU noinline 属性保留两个工作阶段的边界,服务于教学观察;生产归因仍应使用具有代表性的优化构建。GCC 优化选项
C++ runnable demo
#include <array>
#include <cerrno>
#include <charconv>
#include <cstdint>
#include <iostream>
#include <limits>
#include <optional>
#include <stdexcept>
#include <string_view>
#include <system_error>
#include <linux/perf_event.h>
#include <sys/ioctl.h>
#include <sys/syscall.h>
#include <unistd.h>
namespace {
constexpr std::size_t input_size = 4096;
constexpr unsigned maximum_rounds = 2048;
using Input = std::array<std::uint32_t, input_size>;
constexpr std::array<std::uint64_t, 4> expected_pass{
17396735839208ULL, 17684914805289ULL,
17535516519958ULL, 17574288582265ULL};
void require(bool condition, const char* message) {
if (!condition) {
throw std::runtime_error(message);
}
}
unsigned parse_rounds(std::string_view value) {
unsigned rounds = 0;
const auto result = std::from_chars(value.data(), value.data() + value.size(), rounds);
if (result.ec != std::errc{} || result.ptr != value.data() + value.size() ||
rounds == 0 || rounds > maximum_rounds) {
throw std::invalid_argument("rounds must be an integer in [1, 2048]");
}
return rounds;
}
Input make_input() {
Input input{};
for (std::size_t i = 0; i < input.size(); ++i) {
input[i] = (static_cast<std::uint32_t>(i) * 2654435761U) ^ 0xa5a5a5a5U;
}
return input;
}
// GCC/Clang extension: retain useful function boundaries for the example.
// This does not promise complete stacks in a profile of arbitrary libraries.
[[gnu::noinline]] std::uint64_t arithmetic_phase(const Input& input, unsigned salt) {
std::uint64_t sum = 0;
for (const auto value : input) {
std::uint32_t x = value ^ salt;
for (unsigned step = 0; step < 24; ++step) {
x = (x ^ (x >> 13)) * 1664525U + 1013904223U;
}
sum += x;
}
return sum;
}
[[gnu::noinline]] std::uint64_t gather_phase(const Input& input, unsigned salt) {
std::uint64_t sum = 0;
for (std::size_t i = 0; i < input.size(); ++i) {
const auto index = (i * 73U) & (input_size - 1U);
sum += input[index] ^ (salt + static_cast<std::uint32_t>(i));
}
return sum;
}
[[gnu::noinline]] std::uint64_t run_workload(const Input& input, unsigned rounds) {
std::uint64_t checksum = 0;
for (unsigned round = 0; round < rounds; ++round) {
const unsigned salt = round % 4U;
const auto value = arithmetic_phase(input, salt) + gather_phase(input, salt);
require(value == expected_pass[salt], "workload checksum mismatch");
checksum += value;
}
return checksum;
}
struct CounterRead {
std::uint64_t value;
std::uint64_t time_enabled;
std::uint64_t time_running;
};
static_assert(sizeof(CounterRead) == 3 * sizeof(std::uint64_t));
std::optional<long double> scaled_count(const CounterRead& count) {
require(count.time_running <= count.time_enabled, "invalid counter time ordering");
if (count.time_running == 0) {
return std::nullopt;
}
// Convert before multiplying: the integer product could overflow.
return static_cast<long double>(count.value) *
static_cast<long double>(count.time_enabled) /
static_cast<long double>(count.time_running);
}
bool unavailable_configuration(int error) {
// EINVAL can also indicate bad parameters; it does not prove missing hardware.
return error == EACCES || error == EPERM || error == ENOSYS ||
error == ENOENT || error == ENODEV || error == EOPNOTSUPP || error == EINVAL;
}
class TaskClock {
public:
TaskClock() {
perf_event_attr attr{};
attr.type = PERF_TYPE_SOFTWARE;
attr.size = sizeof(attr);
attr.config = PERF_COUNT_SW_TASK_CLOCK;
attr.disabled = 1;
// Request privilege filters, but software task-clock implementations do
// not necessarily split their accumulated clock by privilege level.
attr.exclude_kernel = 1;
attr.exclude_hv = 1;
attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING;
const long result = ::syscall(SYS_perf_event_open, &attr, 0, -1, -1,
PERF_FLAG_FD_CLOEXEC);
if (result < 0) {
const int error = errno;
if (unavailable_configuration(error)) {
std::cout << "SKIP task-clock configuration: perf_event_open errno=" << error << " ("
<< std::generic_category().message(error) << ")\n";
return;
}
throw std::system_error(error, std::generic_category(), "perf_event_open");
}
// A successful Linux fd is an int, despite syscall's long return type.
fd_ = static_cast<int>(result);
}
TaskClock(const TaskClock&) = delete;
TaskClock& operator=(const TaskClock&) = delete;
~TaskClock() {
if (fd_ >= 0) {
::close(fd_); // Linux: do not retry close on EINTR.
}
}
void start() const {
if (fd_ >= 0) {
control(PERF_EVENT_IOC_RESET);
control(PERF_EVENT_IOC_ENABLE);
}
}
void finish() const {
if (fd_ < 0) {
return;
}
control(PERF_EVENT_IOC_DISABLE);
CounterRead count{};
const auto bytes = ::read(fd_, &count, sizeof(count));
if (bytes < 0) {
throw std::system_error(errno, std::generic_category(), "read counter");
}
require(bytes == static_cast<ssize_t>(sizeof(count)), "short counter read");
const auto scaled = scaled_count(count);
std::cout << "task-clock raw=" << count.value
<< " enabled_ns=" << count.time_enabled
<< " running_ns=" << count.time_running;
if (scaled) {
std::cout << " scaled_estimate_ns=" << *scaled << '\n';
} else {
std::cout << " SKIP scaling: counter never ran\n";
}
}
private:
void control(unsigned long request) const {
if (::ioctl(fd_, request, 0) < 0) {
throw std::system_error(errno, std::generic_category(), "counter ioctl");
}
}
int fd_ = -1;
};
void test_helpers() {
require(parse_rounds("1") == 1 && parse_rounds("2048") == maximum_rounds,
"round parsing bounds");
for (const auto bad : {"", "0", "2049", "-1", "1x", " 1", "999999999999999999999"}) {
bool rejected = false;
try {
static_cast<void>(parse_rounds(bad));
} catch (const std::invalid_argument&) {
rejected = true;
}
require(rejected, "invalid rounds accepted");
}
require(!scaled_count({0, 100, 0}), "zero running time must not divide");
require(scaled_count({10, 100, 50}) == 20.0L, "scaling formula");
require(scaled_count({10, 50, 50}) == 10.0L, "unscaled counter");
require(scaled_count({std::numeric_limits<std::uint64_t>::max(), 2, 1}).value() >
static_cast<long double>(std::numeric_limits<std::uint64_t>::max()),
"scale before integer overflow");
bool rejected = false;
try {
static_cast<void>(scaled_count({1, 1, 2}));
} catch (const std::runtime_error&) {
rejected = true;
}
require(rejected, "invalid counter times accepted");
}
} // namespace
int main(int argc, char** argv) {
try {
require(argc <= 2, "usage: perf-flamegraph [rounds: 1..2048]");
const unsigned rounds = argc == 2 ? parse_rounds(argv[1]) : 32U;
test_helpers();
const Input input = make_input();
// Warm and verify all four salts before the measured interval.
static_cast<void>(run_workload(input, 4));
TaskClock counter;
counter.start();
const auto checksum = run_workload(input, rounds);
counter.finish();
std::cout << "rounds=" << rounds << " checksum=" << checksum
<< " correctness=OK\n";
} catch (const std::exception& error) {
std::cerr << "ERROR: " << error.what() << '\n';
return 1;
}
}
Linux 下使用 GCC 或支持对应 GNU 属性的编译器。默认 32 轮,上限 2048;固定输入为 4096 个 uint32_t。arithmetic_phase 做 24 步无符号混合,gather_phase 按固定排列读取同一输入,每轮 salt 在 0 到 3 之间循环。32 位运算有意按模回绕,64 位校验和在本例上界内不会溢出。四个单轮常量通过独立 Python 整数计算并显式截断到 32 位得到,每轮都进行验证。
g++ -std=c++20 -O2 -g -fno-omit-frame-pointer \
-Wall -Wextra -Wpedantic -Werror examples/perf-flamegraph.cpp -o /tmp/perf-flamegraph
/tmp/perf-flamegraph
/tmp/perf-flamegraph 2048
默认输出末行为 rounds=32 checksum=561531645973760 correctness=OK;2048 轮的 checksum 为 35938025342320640。计数成功时会输出原始 task-clock、enabled/running 以及缩放估计;列入可跳过的配置错误时输出带 errno 的 SKIP task-clock configuration,功能负载仍运行。其中 EINVAL 也可能来自参数或组合错误,只表示本次配置未成功,仍需排查,不能断言机器不支持。其他打开错误以及 ioctl/read 失败使程序明确失败。fd 由析构关闭,异常路径也会释放;没有无限重试系统调用。
自测覆盖参数 1 和 2048、空串、零、负数、超范围与尾随字符;缩放覆盖零 running、正常比例、无复用、大数乘法和非法时间顺序。示例没有采样 ring buffer、硬件 PMU 事件或 off-CPU 追踪。SKIP 分支在本次宿主未实际触发,不能据此声称已完成权限拒绝的故障注入。
2026-09-19 的实际环境为 x86-64 WSL2,内核 6.18.33.2-microsoft-standard-WSL2,GCC 13.3.0,perf_event_paranoid=2。perf --version 返回 command not found;直接 perf_event_open 的 task-clock 计数成功。普通默认运行记录过 raw=2621000, enabled_ns=2621000, running_ns=2621000,这只是功能路径的一次观察。没有取得调用栈样本,没有生成火焰图,也没有从这个值推导性能优势。
以下是已有 perf 和 FlameGraph 工具的环境可复核的流程,本次未执行。先确认工具版本、事件支持及用户态采样权限,再运行;若命令失败或没有有效样本,应停止解释结果。$FG 指向已准备好的原作者 FlameGraph 目录,并记录该目录的 Git revision。
perf --version
perf list
perf stat -e task-clock:u -- /tmp/perf-flamegraph 2048
perf record -o perf.data -e cpu-clock:u -F 499 --call-graph dwarf,8192 \
-- /tmp/perf-flamegraph 2048
perf report --stdio -i perf.data
perf script -i perf.data > perf.stacks
"$FG/stackcollapse-perf.pl" perf.stacks > perf.folded
"$FG/flamegraph.pl" perf.folded > perf.svg
先检查 record/report 的丢样、栈质量和实际样本数,再阅读 SVG。上述短负载可能样本不够,不能承诺 -F 499 能得到固定数量;它只是请求频率。外部 record 覆盖整个进程,包括初始化、预热和输出,与内部计数区间不同。比较 FP 与 DWARF 时分别保存文件,不能把两次覆盖和开销差异忽略掉。perf script 负责从真实 perf.data 导出记录;折叠和渲染步骤不补充原始数据中缺失的栈。perf-script(1)
高频追问
为什么不用 Debug 构建找热点?
无优化构建可能保留实际发布程序中已消失的临时对象、调用和内存访问,也可能失去向量化。优先使用代表性的优化参数,加上所需调试和展开信息。若为解释一个机制使用了特殊编译选项,应同时检查目标构建的行为;不能把诊断版本的热点排序直接搬过去。
cpu-clock、cycles 与 cache-misses 能混在一张图里吗?
它们的统计含义不同。CPU 时间采样、硬件周期和缓存事件不能简单相加成同一个时间分布。选择多个事件时需要在导出和聚合时保留事件身份,分别解释。通用缓存事件的 PMU 映射存在处理器差异,硬件中断的采样位置还可能受 skid 影响,应按平台支持选择精确采样能力并核对事件定义。
没有权限时应如何继续?
记录失败的命令、事件、作用范围和 errno,区分 CLI 缺失、权限拒绝、事件不支持和资源不足。perf_event_paranoid 只是权限条件之一,能力、容器策略等也可能影响调用。本章不修改安全配置,也不通过 sudo 放宽限制;在已有授权的可比环境补采集,再记录环境差异。Perf 安全文档
容易答错的点
- “宽度就是一次调用耗时。” 聚合会把多次执行的样本合并;没有调用次数和边界,无法推出单次耗时。
- “最宽的函数就是业务瓶颈。” 它可能是必须执行的高频工作,也可能与当前尾延迟目标无关,需要绝对指标和对照实验。
- “只要
-g就有完整调用栈。” 调试符号和展开条件不同,完整链还受库、优化、栈转储及工具支持影响。 - “提高频率一定更准确。” 样本可能增加,也可能引入更多扰动、限频或丢样;要检查质量和重复结果。
- “scaled count 是实际观测总数。” 复用缩放补的是估计,必须保留运行比例,不能把估计值冒充未复用的原始计数。
性能分析
固定输入 demo 的计算量随 rounds 线性增长,两个阶段各遍历 4096 项,混合步数固定;输入存储为 16 KiB。这个工作集不代表生产行情解析、订单状态更新或跨 NUMA 内存访问。普通校验和 sanitizer 通过只支持功能与有限执行检查,sanitizer 构建的计数不能拿来评估发布性能。
若要比较优化版本,保存硬件型号和拓扑、内核与 perf 版本、二进制 build ID、编译参数、事件配置、CPU/内存放置及工作负载。先预热,再交错重复基线与改动版本,保留各次原始计数和运行比例。当前章节未做这类性能对照,未固定 CPU 或收集完整分布,因此不报告加速比。
采样还应检查丢失记录、unknown 占比、栈截断与内核限频。固定周期负载可能与采样相位相关;稀有尾部路径可能几乎没有样本。减少事件、降低频率或扩大缓冲区各有作用范围,不能只通过增加 SVG 的细节掩盖数据缺口。比较图时同时看有效样本数和绝对 CPU/经过时间,保留原始 perf.data,方便重新选择归因维度。
业务延迟需单独测量。对请求处理记录 p50/p99/p99.9 和吞吐,明确排队是否包含在延迟内。若目标是模拟独立的外部到达流,压测总等上一条完成才发下一条会改变需求并掩盖过载排队。闭环压测适用于相应的交互或依赖响应的业务模型,应按目标选择;CPU 热点图无法替代到达模型的核对。
Quant/Low-Latency 场景
行情处理线程可能把 CPU 用在解码、价格层更新或状态恢复。先用采样缩小到调用路径,再用同一消息轨迹验证,例如减少分配是否降低每条消息 CPU 时间、是否同时改变恢复期间的尾延迟。若批量处理减少函数调用,却延后了较早到达消息的发布,需要将批次等待纳入延迟边界。
另一个常见情况是处理线程平时空闲,突发时 p99.9 升高。CPU 图可能只显示正常处理逻辑,此时要对照入队、开始处理和发出结果的时间,查看排队、调度等待或锁持有者。off-CPU 堆栈描述等待发生的位置,锁持有者为何迟迟不释放还需要相应线程的执行证据,不能把等待者栈当作完整原因。
线上采集本身会消耗资源。先限定线程、事件和持续时间,观察采集开启后吞吐与延迟是否变化;保存原始记录并记录缺失。不能把一次诊断中看到的占比当作所有交易时段都稳定成立的分布。
相关专题
- CPU cache / false sharing:从共享数据布局形成可测量的缓存争用假设。
- NUMA 与 first-touch:解释线程与内存放置如何改变实验条件。
- 虚调用与去虚拟化:理解优化构建的调用结构为何变化。
- mutex 与 condition_variable:把自旋、阻塞和唤醒路径与 CPU/off-CPU 观察对应起来。
分层面试题
题库共 15 道,L1/L2/L3 各 5 道。先练习解释计数和火焰图,再核对复用、栈展开与样本质量,最后用受控实验说明一个归因怎样转化为可验证的性能改动。