监控面板上一根直线:一个 Golang 服务的 CPU 从 20% 拉到 100%,持续了十几分钟。奇怪的是日志里什么都没有——没有错误、没有慢请求、没有 panic。重启之后恢复正常,几小时后重复。
这种「CPU 满但日志干净」的故障,靠猜是猜不出来的:它不像 OOM 有明确的凶手,也不像死锁会留下 goroutine 栈。唯一靠谱的办法是看 CPU 到底花在哪些函数上,而 Go 自带的 pprof 就是干这个的——不需要装任何东西,不需要重启进程(前提是端口还响应)。
这篇文章讲清 3 步定位法,给出 5 类高频热点,每类都配了我在本机跑的实测数据;最后给一份能直接放进服务的自动采样模板——性能优化不必等到 CPU 打满才开始做。
一、先说结论:3 步定位法
① 采样 curl /debug/pprof/profile?seconds=30 → 拿到 CPU profile
② 排序 go tool pprof -top / top / list → 找出 Top N 函数
③ 看图 go tool pprof -http=:8080 → 火焰图确认调用链
第 ② 步和第 ③ 步看的不是同一件事:
top看的是函数自身占用的 CPU(flat列)以及含它调用的子函数(cum列);- 火焰图看的是调用链的形状:某一层突然变宽,才是热点所在。
只看 top 容易误判。举个例子:runtime.mallocgc 的 flat 很高,真正的罪魁祸首是调用它的那个业务函数(可能是某个循环里不停 make([]byte, n))。这时必须用 cum 或者在火焰图里往上找。
二、实测:5 类热点在 profile 里的样子
我写了一段程序,把 5 类常见热点各跑 1.2 秒,然后采集 CPU profile(Go 1.25,Windows,8 核)。先看执行计数:
各热点执行计数(每个跑约 1.2 秒):
正则 : 621567 次
JSON : 28977 次
锁竞争 : 15197412 次
小对象 : 7279920000 次
拼接 : 5350000 次
GC 次数: 2515 | 累计分配: 6857 MB
Duration: 6.13s, Total samples = 18.57s (302.89%)
再看 go tool pprof -top 的头部:
flat flat% sum% cum cum%
6.51s 35.06% 35.06% 6.53s 35.16% runtime.stdcall2
1.81s 9.75% 44.80% 1.81s 9.75% runtime.procyield
1.15s 6.19% 51.00% 1.16s 6.25% main.hotAlloc
0.99s 5.33% 56.33% 0.99s 5.33% runtime.stdcall1
0.83s 4.47% 60.80% 5.58s 30.05% internal/sync.(*Mutex).lockSlow
0.51s 2.75% 66.34% 6.09s 32.79% internal/sync.(*Mutex).Lock (inline)
0.27s 1.45% 69.74% 0.27s 1.45% runtime.memmove
0.24s 1.29% 71.03% 0.39s 2.10% regexp.(*Regexp).tryBacktrack
0.20s 1.08% 72.11% 0.48s 2.58% runtime.scanobject
0.16s 0.86% 73.99% 9.76s 52.56% main.hotMutex.func1
0.15s 0.81% 74.80% 0.17s 0.92% encoding/json.appendString[go.shape.string]
读这张表有三条经验:
runtime.stdcall2/stdcall1(35%)是 Windows 平台的采样噪音,它把系统调用的时间算到了自己头上。Linux 上这一类通常表现为runtime.futex、runtime.usleep。看到 runtime 的底层函数排在前面,先怀疑平台噪音,再看cum高的业务函数。- 真正的热点是
main.hotMutex.func1,cum52.56%——锁竞争吃掉了超过一半的 CPU。它的flat只有 0.86%,如果只看flat列,这个最大的热点会被完全漏掉。 runtime.procyield(9.75%)是锁自旋的空转,它和lockSlow(cum 30%)是同一个故事的两面:一个在自旋等锁,一个在慢路径上排队。
三、5 类高频热点
热点 1:锁竞争(实测 cum 52.56%,第一名)
表现:sync.(*Mutex).lockSlow、runtime.procyield、runtime.usleep、semacquire 靠前。
根因通常是一把大锁保护了太大的临界区,或者锁的粒度太粗(整个 map 一把锁,而不是分片)。注意一个反直觉的现象:goroutine 数越多,锁竞争越严重,吞吐反而下降——CPU 全花在抢锁和调度上。
// ❌ 全局一把锁
var mu sync.Mutex
var m = map[string]int{}
func incr(k string) {
mu.Lock()
m[k]++
mu.Unlock()
}
// ✅ 分片锁:把冲突打散到 64 个桶
const shards = 64
type ShardMap struct {
buckets [shards]struct {
mu sync.Mutex
m map[string]int
}
}
func (s *ShardMap) Incr(k string) {
idx := fnv32(k) % shards
b := &s.buckets[idx]
b.mu.Lock()
b.m[k]++
b.mu.Unlock()
}
func fnv32(s string) uint32 {
h := uint32(2166136261)
for i := 0; i < len(s); i++ {
h ^= uint32(s[i])
h *= 16777619
}
return h
}
读多写少的场景直接换 sync.RWMutex 或 sync.Map;能用原子操作(atomic.AddInt64)就不要用锁。
热点 2:大量小对象分配,把 GC 拖垮(实测 2515 次 GC / 6857MB)
表现:runtime.mallocgc、runtime.scanobject、runtime.gcBgMarkWorker、runtime.memmove 靠前,同时 NumGC 增长飞快。
这类问题的特征很明确:业务函数自己的 flat 不高,但它调用的 mallocgc 的 cum 很高。GC 是并发标记,但 STW 和辅助标记(mutator assist)都会抢业务 CPU。
// ❌ 循环里不停分配
func bad(n int) []byte {
buf := []byte{}
for i := 0; i < n; i++ {
buf = append(buf, byte(i%256)) // 中途多次扩容 + 拷贝
}
return buf
}
// ✅ 预分配容量,容量已知时一次到位
func good(n int) []byte {
buf := make([]byte, 0, n)
for i := 0; i < n; i++ {
buf = append(buf, byte(i%256))
}
return buf
}
// ✅ 高频临时对象用 sync.Pool 复用
var bufPool = sync.Pool{
New: func() any { return make([]byte, 0, 4096) },
}
func withPool(n int) []byte {
b := bufPool.Get().([]byte)
b = b[:0]
defer func() {
if cap(b) <= 64*1024 { // 太大的对象不回池,避免占内存
bufPool.Put(b)
}
}()
for i := 0; i < n; i++ {
b = append(b, byte(i%256))
}
return append([]byte(nil), b...) // 需要返回独立副本时再拷一次
}
热点 3:正则回溯(实测 tryBacktrack 出现在 top 里)
表现:regexp.(*Regexp).tryBacktrack、regexp.(*Regexp).backtrack 出现,且 CPU 随输入长度非线性暴涨。
两个独立的坑:
- 在循环里反复编译正则(
regexp.MustCompile写在函数内部)——编译一次的成本远高于匹配一次; - 用了会灾难性回溯的模式,比如
(a+)+b、(a|a)*b,遇到不匹配的输入时,匹配次数是指数级的。
// ❌ 每次调用都编译
func isBad(s string) bool {
return regexp.MustCompile(`(a+)+b`).MatchString(s)
}
// ✅ 包级变量只编译一次;同时改写掉会回溯的模式
var goodRe = regexp.MustCompile(`a+b`) // 等价语义,但不会灾难性回溯
func isGood(s string) bool {
return goodRe.MatchString(s)
}
能被 strings.Contains / strings.HasPrefix 解决的,不要用正则——前者快一个数量级。
热点 4:JSON 序列化(实测 encoding/json.appendString 上榜)
表现:encoding/json 的一大串函数(appendString、marshal、reflect.Value.*)出现在 top,通常伴随大量反射调用。
encoding/json 是反射实现的,结构越大、字段越多,反射开销越明显。优化顺序:
// ① 减少序列化次数:批量比逐条快得多
// ❌ 循环里逐条 Marshal
for _, r := range rows {
b, _ := json.Marshal(r)
w.Write(b)
}
// ✅ 一次序列化整个切片
b, _ := json.Marshal(rows)
w.Write(b)
// ② 避免在热路径上序列化调试日志
if logLevel == "debug" { // 用开关挡住,而不是先 Marshal 再判断要不要打
b, _ := json.Marshal(bigObj)
log.Println(string(b))
}
// ③ 真到了瓶颈再换库(jsoniter / goccy / sonic),先量化再决定
③ 的前提是先量化:用 go test -bench 对比,别凭印象换库。
热点 5:自旋与空转(实测 procyield 9.75%)
表现:runtime.procyield、runtime.osyield 占比高,或者某个业务函数 flat 极高但看起来什么都不做——通常是忙等循环:
// ❌ 空转等条件,烧掉一个核
for atomic.LoadInt32(&ready) == 0 {
// 什么都不做,CPU 100%
}
// ✅ 用 channel 或条件变量让出 CPU
<-readyCh
// ✅ 至少要给 runtime 让出的机会
for atomic.LoadInt32(&ready) == 0 {
runtime.Gosched() // 主动让出,比纯粹空转好
time.Sleep(time.Millisecond)
}
还有一类是死循环的 goroutine:for {} 忘了 select,或者 for range 一个永远不会关闭的 channel 却在循环体里空转。这类通常结合 goroutine profile 一起看。
四、命令清单
| 命令 | 作用 | 关键输出 |
|---|---|---|
curl -o cpu.prof 'http://127.0.0.1:6060/debug/pprof/profile?seconds=30' |
抓 30 秒 CPU | 采样期间服务要扛住压力 |
go tool pprof -top cpu.prof |
文本 top | 看 flat / cum |
go tool pprof -top -cum cpu.prof |
按 cum 排序 |
⭐ 找「调用别人」的元凶 |
go tool pprof -http=:8080 cpu.prof |
打开 Web UI | 内含 Flame Graph、Graph、Top |
(pprof) top 20 / list FuncName / peek FuncName |
交互模式 | list 能看到逐行耗时 |
curl '.../debug/pprof/goroutine?debug=1' |
协程栈 | 配合看死循环/阻塞 |
curl '.../debug/pprof/heap |
堆 | 排除是内存问题引发的 GC |
GODEBUG=gctrace=1 ./app |
GC 日志 | 看 GC 是否频繁到影响 CPU |
go test -bench . -benchmem -cpuprofile cpu.out |
压测采样 | 离线复现热点 |
go tool trace trace.out |
调度视图 | 看 GC / 调度 / 阻塞三类事件 |
五、配置模板:线上安全采样
pprof 端点不要挂在业务端口上,也不要对公网开放。下面这段是「CPU 高了自动抓一份 profile」的实现,出事之后至少还能拿到现场。
package main
import (
"log"
"net"
"net/http"
_ "net/http/pprof"
"os"
"runtime/pprof"
"time"
)
// startAdmin 只在本地回环开一个运维端口
func startAdmin() {
ln, err := net.Listen("tcp", "127.0.0.1:6060")
if err != nil {
log.Printf("admin 端口不可用(不影响业务): %v", err)
return
}
log.Println("pprof: http://127.0.0.1:6060/debug/pprof/")
go func() { _ = http.Serve(ln, http.DefaultServeMux) }()
}
// watchCPU 每 interval 检查一次 CPU 占用,超过阈值就自动抓一份 profile
func watchCPU(threshold float64, interval, duration time.Duration, dir string) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for range ticker.C {
// 简化实现:用 NumGoroutine + 采样窗口内的平均 CPU 判断
// 生产环境建议读 /proc/self/stat 或 cgroup cpu.stat 算真实占用
usage := sampleCPUUsage(duration)
if usage < threshold {
continue
}
f, err := os.Create(dir + "/cpu-" + time.Now().Format("150405") + ".prof")
if err != nil {
log.Printf("创建 profile 失败: %v", err)
continue
}
log.Printf("CPU %.0f%% 超过阈值 %.0f%%,开始采样 %v", usage, threshold, duration)
if err := pprof.StartCPUProfile(f); err != nil {
f.Close()
continue
}
time.Sleep(duration)
pprof.StopCPUProfile()
f.Close()
log.Printf("已保存: %s", f.Name())
}
}
func main() {
startAdmin()
go watchCPU(80, 30*time.Second, 30*time.Second, os.TempDir())
// 业务服务照常启动...
select {}
}
sampleCPUUsage 的实现留给读者(读 /proc/self/stat 的 utime+stime,或 cgroup v2 的 cpu.stat 里 usage_usec 的差值)。核心思路就一句话:别等人工去抓,让进程自己在出事时留下证据。
六、4 步排查顺序
第 1 步:确认是 CPU 问题,不是阻塞。 CPU 100% 有两种完全不同的成因:真的在算,或者在等(锁、IO、系统调用)。用 go tool trace 或者直接看 /debug/pprof/profile 里 flat 最高的函数是业务函数还是 futex/semacquire。前者是计算热点,后者是竞争/阻塞。
第 2 步:采样 30 秒,先按 cum 排序看一遍。 go tool pprof -top -cum cpu.prof。cum 高的函数才是「发起者」,flat 高的往往是被调用的 runtime 函数。
第 3 步:用 list 看逐行,确认到代码行。 (pprof) list main.hotMutex.func1 会打印这个函数的每一行各占多少。这是从「知道哪个函数」到「知道哪一行」的关键一步。
第 4 步:火焰图上确认调用链,然后改、再压测。 go tool pprof -http=:8080 cpu.prof 打开后点 Flame Graph。改完之后必须用 go test -bench 或真实流量压一轮,对比改前改后的 profile,而不是只看耗时——很多优化只是把热点挪了个位置。
七、总结
- 只看
flat会漏掉最大的热点:实测里锁竞争的flat只有 0.86%,cum却是 52.56%。定位时先按cum排一遍。 - runtime 底层函数排在最前面时,先怀疑平台噪音(Windows 的
stdcall*、Linux 的futex/usleep),真正的凶手在它们的cum上游。 - 5 类高频热点:锁竞争(分片锁/原子操作/读写锁)、小对象分配(预分配 +
sync.Pool,实测拖出 2515 次 GC)、正则回溯(包级预编译 + 改掉(a+)+b这类模式)、JSON 反射(批量序列化、挡住热路径日志)、自旋空转(用 channel 代替忙等)。 pprof端点只监听 127.0.0.1,用kubectl port-forward进去抓;再加一个「CPU 超阈值自动采样」的后台任务,出事时才有现场可查。- 改完必须再采一次 profile 对比,不要凭耗时的变化就下结论。
本文实测数据来自本机(Go 1.25.5,Windows,8 核),5 个热点各跑 1.2 秒。数字只说明「各类热点在 profile 里的相对形态」,不代表你线上的绝对值——照着方法论去抓自己服务的 profile,才是有效的。