LearnDocs 🇨🇳🇨🇳🇨🇳
Benchmark
-
基础说明
- benchmark 和普通的单元测试用例一样,都是在_test.go文件中
- 函数名以Benchmark开头
- b.N 的值大概以 1, 2, 3, 5, 10, 20, 30, 50, 100 这样的序列递增,越到后面,增加得越快
- 参数是
b *testing.B
普通测试用例是b *testing.T
- 运行:
go test -bench .
func BenchmarkFib(b *testing.B) {
time.Sleep(3 * time.Second)
b.ResetTimer() // 重置定时器,避免准备任务的耗时干扰
for n := 0; n < b.N; n++ {
fib(30) // run fib(30) b.N times
}
}
-
参数说明
- 只运行:
go test -bench='Fib$'
- 通过
-cpu
修改cpu的核数,支持传入一个列表 - 通过
-benchtime
修改执行多少次,或者多长时间 5s 或者 30x - 通过
-count
修改benchmark的轮数 3 - 通过
-benchmen
参数查看内存分配情况 - 代码内,
b.ResetTimer()
可以对耗时准备任务的时间进行去除 - 代码内,
b.StopTimer()
和b.StartTimer()
可以跳过准备工作和清理工作
➜ go go test -bench='Fib$' -cpu=1 -benchtime=200x -count=3 -benchmem
goos: darwin
goarch: arm64
pkg: example/go
BenchmarkFib 200 3730384 ns/op 0 B/op 0 allocs/op
BenchmarkFib 200 3677236 ns/op 0 B/op 0 allocs/op
BenchmarkFib 200 3608414 ns/op 0 B/op 0 allocs/op
PASS
ok example/go 2.223s
输出说明
BenchmarkFib-2
多少个cpu上执行的330
执行了多少次3630851
每次执行耗费的ns,换算为0.003s
# 实用命令
go test -benchmem -run=^$ -bench ^BenchmarkProcessReduce$ bsfl/test -count=1 -benchtime=1x -cpu=8 -memprofile=mem.out
go tool pprof mem.out
pprof
# 启动一个wab服务观察
go tool pprof -http=0.0.0.0:8000 http://127.0.0.1:10000/debug/pprof/allocs
go tool pprof -http=:9999 allocs
go tool pprof allocs
# 加载文件
go tool pprof -http=0.0.0.0:8000 -files
# CPU
go tool pprof http://127.0.0.1:10000/debug/pprof/profile
# MEM
go tool pprof http://127.0.0.1:10000/debug/pprof/heap
测试用例
# 生成报告,计算覆盖率
# 生成覆盖率报告文件
go test -v -covermode=count -coverprofile=cover.out
# 使用 go tool 转成 html 格式
go tool cover -html=cover.out -o cover.html