Performance Profiling
Master Linux performance profiling with perf, ftrace, BCC tools, and flame graphs to identify and eliminate kernel bottlenecks.
Master Linux performance profiling with perf, ftrace, BCC tools, and flame graphs to identify and eliminate kernel bottlenecks.
Introduction
Performance profiling is the systematic analysis of where time is spent during program execution. In operating systems, profiling serves two distinct but related purposes: understanding how applications use system resources and diagnosing where the kernel itself spends its time. Without profiling data, optimization is guesswork—developers assume hot paths rather than measure them.
Linux provides several profiling tools for different questions. perf can sample CPU stacks and count hardware events. ftrace traces kernel functions and events, while the BPF Compiler Collection (BCC) supports custom eBPF analysis. Flame graphs make sampled call stacks easier to inspect; measurements are still needed to confirm a suspected bottleneck.
When to Use / When Not to Use
Performance profiling is appropriate when:
- Application runs slower than expected — Quantify where time is actually spent
- CPU utilization is high but throughput is low — Identify lock contention or memory pressure
- Investigating latency spikes — Trace request paths to find blocking operations
- Kernel performance tuning — Understand scheduler behavior, I/O patterns, or interrupt handling
Profiling is NOT appropriate when:
- The problem is obvious from logs — Don’t profile what you already understand
- System is in crisis — Fix known issues first; profiling takes time to set up correctly
- Working on a feature that doesn’t exist yet — Profile production or realistic benchmarks, not speculation
Architecture or Flow Diagram
flowchart TB
subgraph "Data Sources"
PMC[Hardware PMCs<br/>Performance Monitoring Counters]
SWC[Software Counters<br/>tracepoints, kprobes, uprobes]
TIM[Timers<br/>interval sampling]
end
subgraph "Collection Layer"
PERF[perf stat / record]
FTRACE[ftrace<br/>function / wakeup / irq]
BCC[BCC Tools<br/>Python / Lua frontends]
end
subgraph "Analysis Layer"
FG[FlameGraph<br/>stack collapse + svg]
RAPP[rapp<br/>rapport text reports]
STD[perf report<br/>text browser]
end
PMC --> PERF
SWC --> FTRACE
SWC --> BCC
PERF --> STD
PERF --> FG
FTRACE --> FG
BCC --> FG
style FG stroke:#ff6b6b,stroke-width:3px
Core Concepts
perf: The Swiss Army Knife
perf is the primary userspace interface to Linux performance monitoring:
# Basic CPU profiling - record stack traces for 30 seconds
perf record -F 99 -g -a -- sleep 30
# Analyze specific process
perf record -F 100 -g -p $PID -- sleep 10
# Hardware event counting
perf stat -e cycles,instructions,cache-misses -a -- sleep 5
# Profile kernel functions
perf record -g -a --call-graph dwarf sleep 10
# View results
perf report --stdio --symbol-filter='*my_function*'
ftrace: Function-Level Tracing
ftrace provides kernel-internal tracing with minimal overhead:
# Enable function tracer (requires debugfs)
cd /sys/kernel/debug/tracing
echo 0 > tracing_on
echo function > current_tracer
echo my_function > set_ftrace_filter
echo 1 > tracing_on
# Measure function latency with function_graph
echo function_graph > current_tracer
echo 1 > max_graph_depth
# Trace specific events - scheduler latency
echo 1 > events/sched/sched_switch/enable
echo 1 > events/sched/sched_wakeup/enable
cat trace | head -100
BCC Tools for Custom Analysis
BCC provides Python/Lua frontends for eBPF programs:
Tracepoint fields and available BCC helpers depend on the kernel and BCC version. Check the local event format before adapting this example; for openat, Linux exposes it under syscalls/sys_enter_openat on systems that provide that tracepoint.
#!/usr/bin/env python3
"""Example BCC tool: trace file operations by process name"""
from bcc import BPF
from bcc.utils import printb
program = """
#include <uapi/linux/ptrace.h>
#include <linux/sched.h>
struct data_t {
u32 pid;
u32 uid;
char comm[TASK_COMM_LEN];
char filename[256];
};
BPF_PERF_OUTPUT(events);
TRACEPOINT_PROBE(syscalls, sys_enter_openat) {
struct data_t data = {};
data.pid = bpf_get_current_pid_tgid() >> 32;
data.uid = bpf_get_current_uid_gid() & 0xFFFFFFFF;
bpf_get_current_comm(&data.comm, sizeof(data.comm));
bpf_probe_read_user_str(data.filename, sizeof(data.filename),
(const char *)args->filename);
events.perf_submit(args, &data, sizeof(data));
return 0;
}
"""
b = BPF(text=program)
# Print output
def print_event(cpu, data, size):
event = b["events"].event(data)
print(f"{event.pid:6d} {event.comm.decode():16s} {event.filename}")
b["events"].open_perf_buffer(print_event)
while True:
b.perf_buffer_poll()
Generating Flame Graphs
A flame graph summarizes sampled stacks. A wide frame means more samples landed in that function; it does not prove that the function caused the user-visible delay. Compare it with timing measurements and a controlled change before drawing that conclusion.
#!/bin/bash
# Generate flame graph from perf data
PERF_DATA=perf.data
FLAMEGRAPH_DIR=/opt/FlameGraph
# Record profile
perf record -F 99 -a -g -- sleep 30
# Convert to flame graph
perf script | $FLAMEGRAPH_DIR/stackcollapse-perf.pl | \
$FLAMEGRAPH_DIR/flamegraph.pl > profile.svg
# Filter to specific process
perf script | grep myservice | \
$FLAMEGRAPH_DIR/stackcollapse-perf.pl | \
$FLAMEGRAPH_DIR/flamegraph.pl > myservice.svg
Production Failure Scenarios
Scenario 1: Profiling Overhead Swamps Actual Performance
Problem: High sampling rates, broad system-wide captures, or many tracepoints can add enough work to distort the workload being measured.
Profiling has a cost. Sampling interrupts, stack unwinding, and event collection all use CPU time and memory. The overhead depends on the machine, workload, event set, and sampling rate, so do not assume a particular frequency is harmless.
Run the same representative workload once without profiling and once with the planned capture settings. If latency, throughput, or CPU use changes enough to affect the conclusion, reduce the capture scope or sampling rate and measure again.
When you need call graphs, start with a modest frequency such as -F 99 and a short, process-scoped capture. Treat that as a starting point, not a guarantee of low overhead. Broaden the capture only when the question requires it.
Mitigation:
- Record an unprofiled baseline for the same workload
- Start with a small event set and a modest sampling frequency
- Measure the profiler’s overhead under the target workload
- Collect only the processes and time window needed to answer the question
Scenario 2: Unknown or incomplete call stacks
Problem: perf report shows [unknown] frames or corrupted call graphs.
An [unknown] frame can come from missing or mismatched symbols, restricted kernel addresses, JIT code without a symbol map, or a call chain the selected unwinder could not recover. Separate symbol lookup from stack unwinding before changing compiler flags.
Use this checklist:
- Identify which frames are unresolved. Check whether the gaps are in the application, shared libraries, kernel, or JIT-generated code. A resolved instruction address and an incomplete caller chain are different problems.
- Match symbols to the profiled build. Keep the binary’s build ID and matching debug information. Confirm the process did not restart into a different binary between recording and reporting.
- Check kernel symbols separately. Use a
vmlinux/debug-symbol package that matchesuname -r. Access to/proc/kallsymsaddresses may be restricted by kernel policy or capabilities; record that constraint instead of assuming symbols are available. - Check the unwinder. For a build with usable frame pointers, select the frame-pointer unwinder. Otherwise try
perf record --call-graph dwarfand retain the matching debug information. Neither choice repairs missing symbols. - Account for containers and JITs. Make sure the host can see the container’s executable and shared-library build IDs. For JIT code, configure the runtime’s symbol-map support before recording.
- Keep the evidence. Save the exact command, kernel version, binary build ID, unwinder, and permissions with
perf.dataso another engineer can reproduce the symbol resolution.
If only kernel frames are missing, check the running kernel’s symbols and access policy. Do not lower system-wide restrictions just to make one report look complete.
Scenario 3: perf Fails with “Permission Denied”
Problem: /proc/sys/kernel/perf_event_paranoid is set to restrictive values.
Mitigation:
# Check current setting
cat /proc/sys/kernel/perf_event_paranoid
The setting controls which events an unprivileged process may collect, and the exact limits depend on the kernel and granted capabilities. If access is denied, ask the system owner for an approved, least-privilege setup such as CAP_PERFMON, or limit the capture to the target process if policy permits. Avoid lowering the host-wide setting as a routine workaround. See the Linux kernel perf security guide.
Trade-off Table
| Tool | Overhead | Granularity | Customization | Best For |
|---|---|---|---|---|
| perf stat | Very low | Counter totals | Low—preset events | Baseline measurements |
| perf record | Low-Medium | Call stacks | Medium—custom events | CPU hotspot analysis |
| ftrace | Low | Function-level | High—kernel patching | Kernel internals |
| BCC/eBPF | Very low | Custom | Very high | Production tracing |
| FlameGraph | N/A (post-process) | Visual | N/A | Communication |
Implementation Snippet: Custom perf Event
For specialized measurements, create custom tracepoints:
/* In kernel module or tracepoint-enabled code */
#include <linux/tracepoint.h>
/* Define tracepoint in kernel code */
#include <trace/events/sched.h>
void my_sched_function(void)
{
trace_sched_wakeup(p, success);
}
/* Or define custom tracepoint (requires kernel modification) */
/* In include/trace/events/mydevice.h: */
#undef TRACE_SYSTEM
#define TRACE_SYSTEM mydevice
TRACE_EVENT(mydevice_operation,
TP_PROTO(int device_id, size_t bytes, int error),
TP_ARGS(device_id, bytes, error),
TP_STRUCT__entry(
__field(int, device_id)
__field(size_t, bytes)
__field(int, error)
),
TP_fast_assign(
__entry->device_id = device_id;
__entry->bytes = bytes;
__entry->error = error;
),
TP_printk("device=%d bytes=%zu error=%d",
__entry->device_id, __entry->bytes, __entry->error)
);
/* User space then can listen: */
perf stat -e mydevice:mydevice_operation -a -- sleep 5
Observability Checklist
When profiling a production system, collect these metrics in parallel:
- CPU utilization —
mpstat 1for per-core usage - Context switch rate —
vmstat 1, look atcscolumn - Memory pressure —
free -m,cat /proc/meminfo - I/O throughput —
iostat -xz 1 - Network —
netstat -sorss -s - Scheduler latency —
perf sched latency - interrupt distribution —
cat /proc/interrupts
Common Pitfalls / Anti-Patterns
Profiling Methodology
-
Profiling wrong thing — Profiling build time when you should profile runtime, or vice versa. Build time profiling measures compiler behavior: parsing, optimization, code generation. Runtime profiling measures actual execution: CPU cycles, memory access, syscalls. Confusing the two sends you down the wrong path entirely.
-
Ignoring cache effects — First run always looks different; measure warmed cache performance. Cold cache runs trigger page faults, TLB misses, and instruction cache misses that vanish on subsequent runs. Discard first-run data or explicitly warm caches before collecting numbers you want to trust.
-
Microbenchmarking — Measuring small functions in isolation ignores cache, branch prediction, and pipeline effects. A function that looks fast in a microbenchmark may be slow in context because surrounding code evicts it from cache. Profile integrated workloads with realistic data sizes.
-
Over-interpreting samples — A short capture may miss rare work or show a few frames by chance. At 99 Hz over 30 seconds, an idealized capture would collect about 2,970 samples, but the actual count can be lower. Capture longer or repeat the run before treating a rare frame as a hotspot.
Reproducible measurement protocol
For a before/after comparison, keep a short record with the results:
- Build: source revision, compiler/runtime version, optimization flags, and the binary build ID. Keep debug symbols for the exact binary you profile.
- Workload: input size, data set, concurrency, command, and duration. Use the same workload before and after the change.
- Warm-up: say whether the result is cold-start or warmed-cache. Run warm-up iterations outside the measured set when the production path normally reuses code or data.
- Runs: repeat the baseline and changed version under similar load. Report the median and spread, or the mean and standard deviation if using
perf stat --repeat; do not rely on a single run. - Environment: record CPU model, kernel and
perfversions, and whether the capture ran in a container or VM. - Permissions and symbols: note the target-process/system-wide scope, user or capability used, event set, and sampling frequency. Confirm matching user-space build IDs and kernel symbols are available.
- Profiler overhead: compare the workload without profiling and with the planned capture settings. If profiling changes the result enough to affect the conclusion, narrow the capture or lower the sample rate.
Use the same commands, event set, and profiler settings before and after. For example, perf stat --repeat 9 -e cycles,instructions,cache-misses -- ./benchmark repeats the counter run; it does not replace a representative application workload.
Measurement & Attribution
-
Attributing cost incorrectly — A guest’s
systemCPU counters describe guest-accounted execution; they do not reveal how much host CPU time the hypervisor used. In a Linux guest, inspect steal time in/proc/stator thestcolumn fromvmstat 1where available. These metrics can show that the guest was not scheduled, but they do not identify the host-side work responsible. See theproc_stat(5)field definitions andvmstat(8)field definitions.To attribute host-side KVM or VM-exit work, collect a profile on the host.
perf kvm statcan summarize VM exits, andperf kvmsupports host/guest profiling where the kernel, perf build, and permissions allow it; check theperf-kvm(1)manual for the available modes. Record the host kernel and perf versions with the results. Guestperf stat -Aonly changes the guest’s per-CPU view; it cannot compare guest counters with physical-host CPU time. -
Ignoring off-CPU time — Focusing only on CPU-bound analysis misses I/O and lock contention issues. Blocked threads (waiting on I/O, sleeping on locks, scheduled out) do not appear as executing work in an on-CPU profile. A raw
sched:sched_switchtrace records scheduler events, but does not by itself measure how long each thread waited. Use a tool that pairs a thread’s switch-out with its wakeup or switch-in and aggregates the interval, such as BCC’soffcputime, to see where blocked time accumulates.Off-CPU analysis is easy to miss because a blocked thread is not running and cannot contribute an on-CPU sample. For an off-CPU profile, the tool must save the relevant stack at switch-out, observe when the thread runs again, and aggregate the elapsed wait interval. A flame graph built from those duration-weighted stacks can show which call paths account for blocked time; a flame graph from raw switch-event counts cannot establish wait duration.
For example,
sudo offcputime -p 1234 10profiles blocked time for process 1234 over ten seconds on systems where the BCC tool and its required kernel events are available. Check the tool’s local help and permissions first. If a rawperf record -e sched:sched_switchtrace is all you have, treat it as event data that needs additional correlation and duration aggregation, not as an off-CPU time profile by itself.
Tooling & Environment
-
perf_event_paranoid — This sysctl limits the scope of performance events available to unprivileged processes. In current kernel documentation, values of 2 or higher limit unprivileged collection to per-process events while the CPU runs in user space; they do not simply disable most hardware counters. Capabilities, kernel version, event support, and container policy also affect access. Check the Linux kernel perf security guide when diagnosing a permission error. BPF tools have separate capability and policy requirements, so they are not an automatic workaround.
-
Kernel address exposure —
perfcan expose kernel addresses; treat dumps as sensitive. Runningperf recordand thenperf reportoutputs kernel symbol addresses that can aid KASLR bypass in exploitation scenarios. Treat anyperf.datafile as sensitive—do not share it publicly or store it in insecure locations. Useperf --kcoreto capture a core dump mapping kernel addresses for post-mortem analysis in a secure environment only. -
eBPF restrictions — Modern kernels restrict eBPF program capabilities for unprivileged users. While eBPF enables powerful custom instrumentation, the kernel’s BPF verifier limits what unprivileged programs can do. Direct memory access, unbounded loops, and kernel data structure access all require privileges. Enterprise kernels (RHEL, Ubuntu LTS) often restrict eBPF further. If your BPF program fails verification, you need either root/CAP_PERFMON or a kernel patch for that specific capability.
-
DTrace vs perf — Linux perf is less mature than Solaris DTrace; consider SystemTap for complex probes in enterprise environments. DTrace on Solaris offered stable providers with guaranteed API compatibility across kernel versions. Linux perf has no equivalent—kernel internal changes can break dynamic tracepoint probes between versions. SystemTap compiles its scripting language into kernel modules, giving more flexibility than perf but with more risk: a buggy SystemTap script can panic the kernel. For enterprise environments on long-term support kernels, check whether your profiling approach is actually backported and tested for your specific kernel version before relying on it.
Quick Recap Checklist
- Use
perf statfor quick counter summaries before detailed profiling - Use
perf record -gto capture call stacks for hotspot analysis - Use flame graphs to inspect sampled hot paths, then validate a suspected bottleneck with repeated measurements
- ftrace is best for kernel-internal function tracing with low overhead
- BCC/eBPF enables production-safe custom instrumentation without kernel changes
- Always measure baseline before and after changes to verify improvement
- Consider system-wide effects when profiling single applications
Before and after: repeated lookups
This small C++ example replaces a linear scan with an index for a fixed set of keys. It measures only the lookup loop; construction of the unordered_map happens before the timer starts. That suits a workload that reuses the index for many queries. If the real program rebuilds the index often, include that cost too.
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <iostream>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
int main(int argc, char** argv) {
constexpr int key_count = 4096;
constexpr int query_count = 50000;
constexpr int warmup_runs = 2;
constexpr int measured_runs = 9;
const std::string mode = argc > 1 ? argv[1] : "linear";
std::vector<int> keys(key_count);
for (int i = 0; i < key_count; ++i) keys[i] = (i * 7919) % key_count;
std::vector<int> queries(query_count);
std::uint32_t state = 123456789;
for (int& key : queries) {
state = state * 1664525u + 1013904223u;
key = keys[state % key_count];
}
std::unordered_map<int, int> index;
if (mode == "indexed") {
index.reserve(key_count);
for (int key : keys) index.emplace(key, key + 1);
}
auto run = [&]() {
std::uint64_t checksum = 0;
const auto start = std::chrono::steady_clock::now();
for (int key : queries) {
if (mode == "indexed") {
checksum += index.at(key);
} else {
const auto it = std::find(keys.begin(), keys.end(), key);
checksum += *it + 1;
}
}
const auto end = std::chrono::steady_clock::now();
const auto us = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
return std::pair{us, checksum};
};
for (int i = 0; i < warmup_runs; ++i) run();
std::vector<long long> samples;
std::uint64_t checksum = 0;
for (int i = 0; i < measured_runs; ++i) {
const auto [us, result] = run();
samples.push_back(us);
checksum = result;
}
std::sort(samples.begin(), samples.end());
std::cout << mode << " median_us=" << samples[samples.size() / 2]
<< " min_us=" << samples.front() << " max_us=" << samples.back()
<< " checksum=" << checksum << '\n';
}
Build both variants from the same source, then run the two modes:
g++ -O2 -g -fno-omit-frame-pointer -std=c++20 lookup.cpp -o lookup
./lookup linear
./lookup indexed
On one x86-64 workstation (AMD Ryzen 9 5950X, Linux 7.0.0-43-generic, GCC 15.2.0), the two warm-up loops were followed by nine measured loops for each mode:
| Lookup method | Median | Range | Checksum |
|---|---|---|---|
std::find over 4,096 keys |
27,807 µs | 24,860–30,386 µs | 102,420,392 |
Prebuilt std::unordered_map |
129 µs | 129–145 µs | 102,420,392 |
The equal checksums confirm both paths returned the same result. This lookup-only microbenchmark is not an application-wide speedup; it excludes index construction and uses a small, fixed data set. Include setup and update costs, then repeat the comparison with production-sized inputs before choosing a data structure.
The timings use std::chrono::steady_clock. On the host where this example was measured, perf stat could not access hardware counters because perf_event_paranoid was set to 4. No cycle or cache-miss result is claimed here. With approved access, compare counters using perf stat --repeat 9 -e cycles,instructions,cache-misses -- ./lookup linear and the same command with indexed.
Advanced Topic: Speculative Execution and Profiling Errors
Modern CPUs execute instructions speculatively before determining branch outcomes. When profiling with statistical sampling, samples taken during speculative execution can show functions that were never actually on the critical path—the branch was mispredicted and the pipeline was flushed. This leads to false hotspots in your profile.
Mitigations include:
- Use last branch record (LBR) to see actual taken branches, not speculative ones
- Profile with realistic data that exercises real branch patterns
- Use event-based sampling with branch filtering:
perf record -e branch-misses ... - Consider that functions appearing in fewer than 1% of samples may be noise from speculation
Interview Questions
Tracepoints are static, predefined hooks in kernel code that are always compiled in (but can be disabled). kprobes are dynamic instrumentation that attaches to any kernel function entry or any instruction. uprobes are the user-space equivalent, attaching to user-space binary functions. Tracepoints have lowest overhead and stable interfaces; kprobes/uprobes are more flexible but require knowing exact symbol addresses.
Modern CPUs mispredict branches and pipeline instructions speculatively. When a profiler takes a sample during speculative execution, you may see functions in stack traces that weren't actually on the critical path. Use perf record - branches to filter for only taken branches, or rely on last branch record (LBR) when available. Always profile with realistic data that exercises real branch behavior, not synthetic test cases.
perf stat show more cycles than time?Modern CPUs can execute multiple instructions per cycle via pipelining and superscalar execution. "Cycles" counts actual clock cycles elapsed, while "instructions" counts retired instructions. The ratio (cycles per instruction, CPI) reveals pipeline efficiency. If cycles exceed time significantly on a multi-core system, it means the workload is using multiple cores in parallel—each core contributing its own cycles.
eBPF (extended Berkeley Packet Filter) allows sandboxed programs to run in the kernel without modifying kernel source or loading modules. Programs are verified for safety before execution and can be attached to kprobes, tracepoints, or network interfaces. This enables custom metrics collection, networking, and security enforcement—all without kernel patches. BCC provides high-level languages (Python, Lua) that compile to eBPF bytecode.
Statistical sampling at 99Hz or 999Hz cannot reliably capture microsecond-scale functions—they may not appear in any sample. Instead, use: (1) perf stat -e with cache miss or branch misprediction events that correlate with the function; (2) instruction counting via perf stat -e instructions; (3) trace the specific function with ftrace and its graph mode to measure individual calls; (4) consider if the function needs algorithm optimization rather than just measurement.
Hardware PMCs (Performance Monitoring Counters) are built into the CPU and count events like cycles, instructions, cache misses, and branch mispredictions—they require minimal overhead to read. Software counters are implemented by the kernel via tracepoints and kprobes; they count events like context switches, page faults, and scheduler decisions. Hardware counters provide lower overhead and higher precision for CPU-bound analysis; software counters provide visibility into kernel activities that have no hardware equivalent.
When a PMC overflows (reaches its maximum count), the kernel receives an interrupt and records a sample with the current instruction pointer. For continuous monitoring with overflow handling, use perf record -f to use frequency-based sampling where the kernel reprograms the counter after each sample rather than waiting for overflow. The perf_event_attr::watermark setting controls when the overflow interrupt fires. In multi-threaded programs, the kernel uses inherit settings to decide whether children inherit the parent's events.
perf uses a per-CPU ring buffer (struct ring_buffer) to transfer samples from kernel to user space. When perf records, itmmaps the buffer and the kernel writes samples directly into it without syscalls per sample—only a single mmapped region update. When the buffer is full, perf loses samples (in overwrite mode) or blocks (in per-CPU mode). Using perf record -m 2 increases the buffer size to reduce sample loss in high-frequency profiling scenarios.
ftrace excels at function-level tracing with minimal overhead—its function tracer can be enabled with just echo function > current_tracer. perf is better for hardware event counting and call graph analysis. Choose ftrace when you need: (1) function-level visibility with low overhead, (2) kernel function latency via function_graph, (3) tracepoint filtering with event parameters, (4) dynamic instrumentation with kprobe events. Choose perf when you need hardware metrics, call stacks, or userspace tracing.
Flame graphs show relative time spent in each function stack—wider boxes mean more samples. The vertical axis shows ancestry (caller on top, callee below); horizontal position has no meaning. To interpret: (1) find the widest blocks—these are your hottest paths; (2) read from root to leaf to understand call sequences; (3) compare flame graphs before/after changes to verify improvement; (4) look for "plateaus" of similar frame widths—these often indicate a bottleneck where all callers converge. The colors are typically cosmetic unless you enable hue-by-attribute.
On-CPU profiling samples code while a thread is running. For a blocked-time profile, use a tool that pairs a thread's switch-out with its wakeup or switch-in and sums the wait interval, such as BCC's offcputime (for example, sudo offcputime -p 1234 10). A raw perf record -e sched:sched_switch capture records scheduler events, but by itself it does not aggregate blocked duration by stack. See the BCC offcputime examples. Tool availability and required privileges depend on the Linux system.
LBR is a hardware feature that stores the last N (typically 16-32) branch records including source and destination addresses. Unlike standard sampling that interrupts periodically and captures only the current instruction pointer, LBR captures actual taken branches with their destinations. This is crucial because: (1) it eliminates speculation noise—branches that were mispredicted and flushed from pipeline don't appear as real work; (2) it provides precise call chains without frame pointers; (3) it enables perf record -j any,u -- branches to capture all branch events efficiently. Enable with perf record -j any,u -a and view with perf report --branch-history.
Cache misses don't directly measure memory latency—they measure miss events. When a cache miss occurs, the CPU waits (stalls) for data from memory, but a single cache-misses counter event doesn't tell you how long each stall lasted. To correlate misses with latency: (1) use perf stat -e cycles,cache-misses,cache-references and calculate miss rate; (2) combine with stalled-cycles-frontend and stalled-cycles-backend to see how much of the pipeline is waiting; (3) use perf record -e cache-misses -W with weight to capture miss latency; (4) consider using memory-latency events on Intel (cbo_X events) for actual memory access latency histograms.
CPI is cycles / instructions, the average cycles per retired instruction for the measured event set. There is no universal cutoff: the value depends on the CPU, workload, event support, and counter multiplexing. A high CPI alone does not identify memory latency, branch stalls, or another cause. Compare repeated measurements on the same workload and machine, then inspect relevant counters and sampled stacks. Low CPU utilization only says the CPU was not kept busy during that interval; it can reflect I/O, locks, sleeps, CPU limits, or available idle capacity, and does not explain the CPI by itself.
Dynamic module loading creates profiling challenges because symbols may not be available when perf isn't running. Solutions: (1) Build modules with debug symbols and install to /lib/modules/$(uname -r)/build—perf will find them automatically; (2) Use module.symbols file to map dynamic addresses to names after the fact; (3) Persistently enable tracing with ftrace before running workload—ftrace can capture module function entries even without symbol resolution; (4) Use BPF with kprobe on module functions: BPF programs attached to module symbols will auto-load when the module loads; (5) For post-mortem analysis, use perf record -k mono -g with mono (monotonic clock) for ordering.
AMD's IBS (Instruction-Based Sampling) provides more detailed profiling than standard PMCs. IBS periodically triggers based on: Fetches—instruction fetch cycles and op information; Ops—micro-ops retired and their characteristics. Unlike standard PMCs which count events (cache misses, branches), IBS provides exact instruction addresses that caused events. Benefits: (1) more precise hotspot identification without frame pointer dependency; (2) micro-op level visibility for AMD Zen architectures; (3) better handling of instruction cache misses. Access via perf record -e ibs_fetch/.../ -e ibs_op/.../. Intel equivalents are PEBS (Precise Event-Based Sampling) and LBR (Last Branch Record).
False sharing occurs when threads on different cores modify variables that share the same cache line, causing unnecessary cache invalidations. Profiling indicators: (1) High cache-misses with low memory traffic—many invalidations but not much data transferred; (2) perf stat showing high cache_misses and store_blocks ld_flood events; (3) High context switch rates between threads that access related data structures. Confirmation: use perf c2c record (cache-to-cache analysis) which shows cache line contention events including ld_l1hit, ld_l2hit, stores with RFO (Read-For-Ownership) that indicate cache line bouncing. Fix: pad data structures to ensure each thread's data is cache-line-aligned.
--call-graph dwarf unwinds user stacks using DWARF Call Frame Information (CFI), where the binary or matching unwind data provides it. Full debug symbols are not required for unwinding, though separate debug information helps resolve function names and source lines. This mode records stack bytes and usually has more overhead than frame-pointer unwinding. --call-graph fp follows frame-pointer chains and needs code built with frame pointers; builds that omit them can produce incomplete call chains. See the perf record call-graph documentation for supported modes and options.
The perf_event_paranoid sysctl sets the scope of perf events available to unprivileged processes. The Linux kernel documentation describes these thresholds:
- -1: No perf-events scope or access restrictions.
- 0 or higher: Per-process and system-wide monitoring are in scope, but raw tracepoints and ftrace function tracepoints are excluded.
- 1 or higher: System-wide monitoring is excluded; per-process events remain in scope.
- 2 or higher: Unprivileged monitoring is limited to per-process events while the CPU runs in user space.
Capabilities and system policy can change these access checks. When access is denied, ask the system owner about an approved least-privilege setup such as CAP_PERFMON, and check the kernel perf security guide for the running kernel.
BPF maps can exhibit staleness when the kernel is in the middle of updating them while userspace is reading. Key issues: (1) Lookup vs Update race: bpf_map_lookup_elem() may return a value that's being concurrently modified; (2) Incremental updates: when aggregating in-kernel, userspace might see partial results. Mitigations: (1) use BPF_F_NO_PREALLOC for atomic map allocation; (2) use bpf_percpu_hash for per-CPU aggregation which avoids cross-CPU synchronization; (3) implement double buffering in userspace—read from one map while the kernel writes to another, then swap; (4) use __sync_fetch_and_add for atomic increments. For production tracing, consider using ring_buffer (available in Linux 5.8+) which supports efficient, lock-free data transfer.
Further Reading
- Brendan Gregg’s perf Tools - Comprehensive perf examples and flame graph creation
- BPF Performance Tools - eBPF tools for Linux observability
- Linux perf Examples - One-minute tutorials with real examples
- LWN.net: The perf tools - Deep dive into perf internals
- Kernel Profiling with perf - Official kernel profiling guide
- Kernel Module Development — Write kernel modules for custom profiling
- Buffer Cache and Page Cache — Understand memory subsystem performance
Conclusion
Profiling helps answer a narrower question: where did this workload spend time during this run? Linux provides several ways to investigate, including perf for counters and sampled call stacks, ftrace for kernel tracing, and BCC/eBPF for custom instrumentation. Each tool has its own access requirements and overhead.
Start with a baseline on the same workload. A flame graph can point to a hot path, but it cannot prove that path caused a user-visible problem. Change one thing, then repeat the measurement with the same build settings, data, and profiler configuration. Check the profiler’s overhead before trusting a small difference.
For continued learning, explore kernel profiling with perf inside containers, eBPF programs for custom latency histograms, and hardware performance monitoring with last branch records (LBR) for speculative execution analysis.
Category
Related Posts
Logging, Processes, and Permissions on Hosts
Learn how host users, process identities, file permissions, services, and system logs fit together, with safe read-only checks for Linux systems.
Ethernet, ARP, and Neighbor Discovery Explained
Learn how Ethernet frames, switches, VLANs, ARP, and IPv6 Neighbor Discovery deliver packets on a local link, with Linux diagnostics and failure examples.
IP Routing and NAT: How Packets Cross Networks
Learn how routers choose paths with routing tables, longest-prefix match, and gateways, then see how NAT and port translation change packets at network edges.