Go / 系统课时

搭建 Go 并发性能实验环境

搭建 Go 并发性能实验环境

本课搭建一套可重复运行的 Go 1.26 并发性能实验环境,用 testing 产生稳定基线,再用 pprof、trace 和运行时开关分别观察 CPU、内存、调度与执行时序。

学习目标

  • 建立 Go 1.26 的最小性能实验项目,并用 benchmark 固定测试入口
  • 生成并读取 CPU、内存 profile 与 execution trace
  • 使用 GOMAXPROCS、GODEBUG 等开关构造可比较的实验条件

固定实验基线

先确认工具链版本。Go 1.26 于 2026 年 2 月发布,本课直接以该版本作为实验基线;实际运行时建议固定到同一 1.26.x 修订版,避免不同补丁版本带来的工具链差异。:contentReference[oaicite:0]{index=0}

项目目录保持简单,只保留 go.mod 和一个 benchmark 文件。benchmark 必须有稳定的输入规模,否则后续 profile 很难比较。

创建文件 lab/lab_test.go:

go
package lab

import (
	"crypto/sha256"
	"testing"
)

func BenchmarkConcurrentWork(b *testing.B) {
	data := make([]byte, 4<<10)
	for i := range data {
		data[i] = byte(i)
	}

	b.ResetTimer()
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			// 固定输入规模,避免 profile 被随机业务数据干扰。
			_ = sha256.Sum256(data)
		}
	})
}

生成 profile 与 trace

先建立模块并执行基准测试:

bash
go mod init example.com/concurrency-lab
go test ./lab -run=^$ -bench=BenchmarkConcurrentWork -benchtime=2s -count=1 -cpuprofile=cpu.prof -memprofile=mem.prof -trace=trace.out

预期结果:

text
go: creating new go.mod: module example.com/concurrency-lab
...
BenchmarkConcurrentWork-<N>    <COUNT>    <NS_PER_OP> ns/op
PASS
ok      example.com/concurrency-lab/lab    <TIME>

一次 benchmark 可以同时生成 CPU profile、内存 profile 和 trace。Go 官方文档明确支持通过 go test 的 benchmark 参数直接写出这些分析文件;runtime/pprof 产生的数据可交给 go tool pprof 分析。:contentReference[oaicite:1]{index=1}

读取 CPU 与内存证据

先看 CPU 热点,再看内存分配热点:

bash
go tool pprof -top cpu.prof
go tool pprof -top mem.prof

预期结果:

text
Showing nodes accounting for a large share of samples, total ...
      flat  flat%   sum%        cum   cum%
      ...    ...     ...         ...    ...

Showing nodes accounting for a large share of samples, total ...
      flat  flat%   sum%        cum   cum%
      ...    ...     ...         ...    ...

这里关注的是“哪个调用路径消耗资源”,而不是只看某个函数名。CPU profile 反映主动消耗 CPU 周期的时间;heap profile 则用于观察内存分配样本,两者回答的问题不同。:contentReference[oaicite:2]{index=2}

需要图形化查看时,可以直接启动 pprof Web UI:

bash
go tool pprof -http=127.0.0.1:<PORT> cpu.prof

预期结果:

text
Serving web UI on http://127.0.0.1:<PORT>

Go 1.26 的 pprof Web UI 默认进入 flame graph 视图,原有 graph 视图仍可从界面菜单进入。:contentReference[oaicite:3]{index=3}

观察执行时序

trace.out 不等同于 CPU profile。execution trace 记录 goroutine 创建、阻塞与唤醒、系统调用、GC、P 的启停等运行时事件,因此更适合回答“为什么这里等待了这么久”以及“调度发生了什么”。:contentReference[oaicite:4]{index=4}

使用:

bash
go tool trace trace.out

预期结果:

text
Serving web UI on http://127.0.0.1:<PORT>

测试和 benchmark 原生支持 go test -trace 生成 trace,因此优先从 benchmark 采集通常比给业务程序额外植入采集逻辑更容易复现。:contentReference[oaicite:5]{index=5}

用运行时开关做对照实验

同一 benchmark 至少保留一个默认基线,再改变并发运行参数重新采集。GOMAXPROCS 控制可同时执行 Go 代码的逻辑处理器数量;GODEBUG 可打开运行时诊断事件,例如 schedtrace 周期性输出调度状态,gctrace 输出 GC 事件。:contentReference[oaicite:6]{index=6}

例如先固定较小的并行度:

bash
GOMAXPROCS=2 go test ./lab -run=^$ -bench=BenchmarkConcurrentWork -benchtime=2s -count=1

预期结果:

text
BenchmarkConcurrentWork-2    <COUNT>    <NS_PER_OP> ns/op
PASS
ok      example.com/concurrency-lab/lab    <TIME>

再打开调度事件:

bash
GODEBUG=schedtrace=1000,scheddetail=1 GOMAXPROCS=2 go test ./lab -run=^$ -bench=BenchmarkConcurrentWork -benchtime=2s -count=1

预期结果:

text
SCHED <TIME>ms: gomaxprocs=2 idleprocs=... threads=... spinningthreads=... runqueue=... [...]
BenchmarkConcurrentWork-2    <COUNT>    <NS_PER_OP> ns/op
PASS
ok      example.com/concurrency-lab/lab    <TIME>

实验时不要同时开启大量诊断项。官方文档特别提醒,某些 profile 会互相干扰,例如精确内存 profiling 会影响 CPU profile,而 goroutine blocking profile 也可能影响 scheduler trace。最可靠的做法是一次只回答一个问题。:contentReference[oaicite:7]{index=7}

环境搭好后,固定 Go 版本、测试输入、benchmark 参数和运行时开关,再保存 cpu.prof、mem.prof、trace.out。这样后续任何性能优化都能在同一基线下比较,而不是凭一次运行的偶然快慢下结论。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

搭建 Go 并发性能实验环境

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通