提示:本网站现在为维护调试状态

Linux Performance Tuning: perf, bpftrace & BCC

Choyeon
Choyeon
Sep 11, 2026 1 min read 364 Views
437 words 2,421 chars Updated Nov 8, 2026
Linux Performance Tuning: perf, bpftrace & BCC
Table of contents

The USE Method guides production debugging: first measure Utilization, Saturation, and Errors for each resource, then deep-dive with specific tools. This covers today's three most important tools.

perf_events: CPU-level Hotspot Analysis

perf uses CPU PMU hardware counters with tiny overhead (~2%). Sample at 99Hz to avoid lock-step with scheduler periodicity for accurate distributions. perf stat captures macro metrics; perf record + FlameGraph builds interactive visualizations.

#!/usr/bin/env bash
set -euo pipefail
LOG=perf-report-$(date +%Y%m%d-%H%M).log
exec > >(tee -a "$LOG") 2>&1

echo "===== [1] CPU TOP functions 30s ====="
perf record -F 99 -a -g -- sleep 30
perf report --stdio -n --sort comm,dso,symbol | head -60
# perf script | FlameGraph/stackcollapse-perf.pl | flamegraph.pl > cpu-flame.svg

echo "\n===== [2] perf stat system-wide ====="
perf stat -a -d -- sleep 10
# 关注 context-switches, cache-misses 比率, stalled-cycles-frontend

echo "\n===== [3] bpftrace: block IO size distribution by comm ====="
bpftrace -e '
tracepoint:block:block_rq_issue { @[comm, args->rwbs[0]] = hist(args->bytes); }
interval:s:15 { printf("\n=== 15s IO hist by process ===\n"); print(@); clear(@); exit(); }
' 2>&1 | head -40 || true

echo "\n===== [4] bpftrace: TCP active connect trace ====="
bpftrace -e '
kprobe:tcp_connect { printf("PID %d (%s) -> %s\n", pid, comm, ntop(args->family, args->daddr)); }
' -c 'curl -s https://example.com >/dev/null' 2>&1 | head -20 || true

echo "\n===== [5] BCC biolatency + tcplife ====="
/usr/share/bcc/tools/biolatency -mF 1 5 || true
# /usr/share/bcc/tools/offcputime -df 5 1 > offcpu.stacks
timeout 15 /usr/share/bcc/tools/tcplife -L -T 2>/dev/null | head -40 || true

echo "\n===== [6] snapshot vmstat slabtop sar ====="
vmstat 1 5
echo "--- slab top ---"
slabtop -o -s c | head -25 || true
echo "--- THP check ---"
grep -E "AnonHugePages|HugePages_Total" /proc/meminfo || true
echo "\nSaved to: $LOG"

bpftrace and BCC: Kernel Event Tracing

eBPF attaches sandboxed C programs to kernel functions, tracepoints, USDT probes. bpftrace excels at one-liner rapid investigations. BCC ships 200+ prepackaged tools; biolatency, offcputime, and tcplife are your triad for IO/block/network latency triage.

Resource Dimension Macro Triage (orientation) Micro Diagnostic (deep dive)
CPU top/vmstat us,sy,wa,st cols perf record + FlameGraph
Scheduler latency /proc/schedstat pidstat -w BCC runqlat bpftrace sched_switch
Memory free/vmstat si,so sar -r BCC memleak perf kmem slabtop
Disk IO iostat -xz await/util% BCC biolatency bpftrace block_rq_*
Network latency ss -ti/sar -n TCP,ETCP BCC tcplife bpftrace tcp:probe

Best Practices

Macro before micro: start with sar/vmstat to classify which resource type is the issue, then pick right BCC tools, finally drop into custom perf/bpftrace. eBPF is privileged; validate scripts in staging first and limit production runs to few minutes at a time.

X微博Telegram

About the author

Poll

你最希望 Rosetta 优先加入哪项功能?

社区投票(演示数据,可后台删除)

Comments (3)

0 / 3000
DevOps小能手
DevOps小能手devops-lab.cnOct 1, 2026

写得太好了,终于搞懂了分布式事务的几种方案区别,收藏了!

技术笔记控
技术笔记控tech-notes.funOct 1, 2026

作为一个刚入行的后端新人,这篇文章帮我理清了好多概念,谢谢博主持续输出高质量内容!

画画的小鱼
画画的小鱼fishgallery.artSep 30, 2026

代码示例里那个 SQL 查询是不是应该加个 LIMIT?不然数据量大的时候全表扫描会很慢哦。

Related posts

Rust Ownership & Borrowing: Lifetimes Explained

Rust Ownership & Borrowing: Lifetimes Explained

Master Rust's most unique concepts: ownership rules, mutable/immutable borrowing constraints, lifetime annotations. Compile-error examples + fixes to think like the Borrow Checker for safe zero-cost code.

1 min read
PostgreSQL Query Optimization Techniques

PostgreSQL Query Optimization Techniques

Master PostgreSQL optimization: EXPLAIN ANALYZE plans, choosing index types (B-tree/GIN/BRIN), updating statistics, tuning joins, and partitioned table design for maximum performance.

1 min read
Getting Started with WebAssembly: Rust to WASM + JS

Getting Started with WebAssembly: Rust to WASM + JS

End-to-end Rust to WASM setup: wasm-pack toolchain, wasm-bindgen type bindings, JS sync/async invocation, TypedArray memory sharing for compute-heavy browser workloads.

1 min read
Zero Trust Security Architecture: Never Trust, Always Verify

Zero Trust Security Architecture: Never Trust, Always Verify

Zero Trust security model primer: built on "never trust, always verify" and dismantles traditional VPN-equals-trusted perimeter thinking. Six pillars explained — identity (MFA/SAML), device health checks, least-privilege RBAC, microsegmentation mTLS, continuous trust scoring, observable audit trail — with implementation roadmap.

1 min read
K8s Pod Lifecycle, Init Containers & Sidecars

K8s Pod Lifecycle, Init Containers & Sidecars

Full K8s Pod state machine Pending→Terminated, PostStart/PreStop hooks, Init Container dependency guarantees, Sidecar patterns (istio-proxy, log collectors), and zero-downtime graceful termination configs.

1 min read
Test Pyramid: Unit/Integration/E2E Ratios & Implementation

Test Pyramid: Unit/Integration/E2E Ratios & Implementation

Systematic test pyramid breakdown: bottom unit tests (many, fast, mock isolated), middle integration tests (real service/db/message interaction), top E2E tests (few, critical user flows). Recommended ratio 70/20/10, with coverage metrics and implementation playbook.

1 min read