写性能测试在Go语言中是很便捷的,go自带的标准工具链就有完善的支持,下面我们来从Go的内部和系统调用方面来详细剖析一下Benchmark这块。
Benchmark
Go做Benchmark只要在目录下创建一个_test.go后缀的文件,然后添加下面函数:
func BenchmarkStringJoin1(b *testing.B) {
b.ReportAllocs()
input := []string{"Hello", "World"}
for i := 0; i < b.N; i++ {
result := strings.Join(input, " ")
if result != "Hello World" {
b.Error("Unexpected result: " + result)
}
}
}
调用以下命令:
# go test -run=xxx -bench=. -benchtime="3s" -cpuprofile profile_cpu.out
该命令会跳过单元测试,执行所有benchmark,同时生产一个cup性能描述文件。
注意
·-benchtime 可以控制benchmark的运行时间
·b.ReportAllocs(),在report中包含内存分配信息,例如结果是:
BenchmarkStringJoin1-4 300000 4351 ns/op 32 B/op 2 allocs/op
-4表示4个CPU线程执行,3000000表示总共执行了30万次;4531ns/op,表示每此执行耗时4531纳秒;32B/op表示每次执行分配了32字节内存;2allocs/op表示每次执行分配了2次对象。
根据上面的信息,我们就能对热点路径进行内存对象分配的优化,例如针对上面的程序我们可以小小的优化:
func BenchmarkStringJoin2(b *testing.B) {
b.ReportAllocs()
input := []string{"Hello", "World"}
join := func(strs []string, delim string) string {
if len(strs) == 2 {
return strs[0] + delim + strs[1];
}
return "";
};
for i := 0; i < b.N; i++ {
result := join(input, " ")
if result !

本文介绍了在Go语言中进行性能测试的方法,通过Benchmark工具分析代码执行时间和内存分配。并探讨了如何利用CPU Profile发现性能瓶颈,展示了如何生成和解读CPU性能报告,以及如何通过火焰图进一步优化代码,提升性能。
最低0.47元/天 解锁文章
775

被折叠的 条评论
为什么被折叠?



