性能分析:基准测试与 pprof
用基准测试比较耗时和内存分配,再用 CPU profile 定位耗时的代码。
先测量:比较两种拼接方式
把一批订单编号拼成一行时,可以在循环里用 += 追加,也可以用 strings.Builder。编号越多,反复拼接已有字符串时,复制的内容就越多。下面的基准为两种实现准备同一批输入,测量只覆盖拼接过程。
在空目录运行 go mod init example.com/report,把代码保存为 report_test.go:
package report
import (
"strconv"
"strings"
"testing"
)
func joinConcat(parts []string) string {
var out string
for i, part := range parts {
if i > 0 {
out += ","
}
out += part
}
return out
}
func joinBuilder(parts []string) string {
var out strings.Builder
for i, part := range parts {
if i > 0 {
out.WriteByte(',')
}
out.WriteString(part)
}
return out.String()
}
func orderIDs() []string {
parts := make([]string, 100)
for i := range parts {
parts[i] = "order-" + strconv.Itoa(i)
}
return parts
}
func TestJoinReport(t *testing.T) {
for _, parts := range [][]string{nil, {"order-1"}, orderIDs()} {
want := strings.Join(parts, ",")
if joinConcat(parts) != want || joinBuilder(parts) != want {
t.Fatalf("拼接结果不符,输入长度:%d", len(parts))
}
}
}
var result string
func benchmarkJoin(b *testing.B, join func([]string) string) {
parts := orderIDs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
result = join(parts)
}
}
func BenchmarkJoinConcat(b *testing.B) { benchmarkJoin(b, joinConcat) }
func BenchmarkJoinBuilder(b *testing.B) { benchmarkJoin(b, joinBuilder) }
go test
go test -run '^$' -bench '^BenchmarkJoin' -benchmem -count 3
第一条命令检查两种实现是否返回预期结果。第二条跳过普通测试,匹配以 BenchmarkJoin 开头的基准,并各运行三次。测试框架会调整 b.N,使每轮有足够多次操作;b.ResetTimer() 排除准备输入的时间和分配统计,包级变量 result 则让计算结果被保留。
| 输出列 | 表示什么 |
|---|---|
ns/op | 每次拼接平均消耗多少纳秒 |
B/op | 每次拼接平均分配多少字节 |
allocs/op | 每次拼接平均分配多少次 |
对比多次结果,确认差异是否稳定。这个示例通常可以看到 Builder 减少分配;具体数字会随输入大小、Go 版本和机器变化,不能用来推断整个服务会快多少。
再定位:用 CPU profile 看时间花在哪
只运行拼接较慢的基准,收集 CPU 样本:
go test -run '^$' -bench '^BenchmarkJoinConcat$' -benchtime 2s -cpuprofile cpu.out -o report.test
go tool pprof -top report.test cpu.out
flat 是直接归在该函数上的 CPU 样本;cum 还包含它调用的函数。即使 joinConcat 自己的 flat 不高,仍可看它的 cum,再检查字符串拼接、复制和分配相关的函数有没有出现在列表上。CPU profile 记录的是 CPU 活动,不能直接解释等待网络或磁盘所花的时间。
找到可疑开销后,只改一个因素,再用同样的输入和命令跑测试与基准。如果实际需求只是用分隔符连接字符串,优先考虑 strings.Join;还要在拼接过程中有条件地写入内容时,再考虑 Builder。