对 Golang 程序进行性能优化,可以在提升业务收益的同时,起到降低成本的作用。
Benchmark 示例
go
func BenchmarkConvertReflect(b *testing.B) {
var v interface{} = int32(64)
for i:=0;i<b.N;i++{
f := reflect.ValueOf(v).Int()
if f != int64(64){
b.Error("errror")
}
}
}
函数固定以 Benchmark 开头,其位于_test.go 文件中,入参为 testing.B ,业务逻辑应放在 for 循环中,因为 b.N 会依次取值 1, 2, 3, 5, 10, 20, 30, 50,100.........,直至执行时间超过 1s
可以运行 go test -bench 命令执行 benchmark,其结果如下:
go
go test -bench='BenchmarkConvertReflect' -run=none
goos: darwin
goarch: amd64
pkg: gotest666
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkConvertReflect-12 520200014 2.291 ns/op
-
--bench='BenchmarkConvertReflect', 要执行的benchmark。需注意:该参数支持模糊匹配,如--bench='Get|Set',支持./...-run=none,只进行Benchmark,不执行单测 -
BenchmarkConvertReflect, 在12核下,1s内执行了520200014次,每次约2.291ns。
高级用法
go
go test -bench='Convert' -run=none -benchtime=2s -count=3 -cpu='2,4' -benchmem -cpuprofile=cpu.profile -memprofile=mem.profile -blockprofile=blk.profile -trace=trace.out -gcflags=all=-l
goos: darwin
goarch: amd64
pkg: gotest666
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkConvertReflect-2 1000000000 2.286 ns/op 0 B/op 0 allocs/op
BenchmarkConvertReflect-2 1000000000 2.302 ns/op 0 B/op 0 allocs/op
BenchmarkConvertReflect-2 1000000000 2.239 ns/op 0 B/op 0 allocs/op
BenchmarkConvertReflect-4 1000000000 2.244 ns/op 0 B/op 0 allocs/op
BenchmarkConvertReflect-4 1000000000 2.236 ns/op 0 B/op 0 allocs/op
BenchmarkConvertReflect-4 1000000000 2.247 ns/op 0 B/op 0 allocs/op
PASS
-benchtime=2s, 依次递增b.N直至运行时间超过2s-count=3,执行3轮-benchmem,-b.ReportAllocs,展示堆分配信息,0 B/op,0 allos/op分别代表每次分配了多少空间,每个op有多少次空间分配-cpu='2,4',依次在2核、4核下进行测试-cpuprofile=xxxx -memprofile=xxx -trace=trace.out,benmark时生成profile、trace文件-gcflags=all=-l,停止编译器的内联优化