性能测试基本概念
基本概念
Benchmark: 性能测试
ns/op: 纳秒/每个操作,前面数值越小越快
命令
- go test -c
- go test -test.bench=. -test.cpuprofile=cpu.prof
- go tool pprof bench.test cpu.prof
示例
建立一个包,创建一个test文件如,文件名为lib_test.go
package lib
import (
"testing"
"fmt"
)
const (
str = "hello gohpers!"
sep = ","
)
func BenchmarkFmt(b *testing.B) {
for i := 0; i < b.N ; i++ {
_ = fmt.Sprintf("%s%s%s%s%s", str, sep, str, sep, str)
}
}
func BenchmarkPlus(b *testing.B) {
for i:=0; i < b.N; i++ {
_ = str + sep + str + sep + str
}
}
然后运行 go test -bench=.
后面这个参数"." 不能加引号
结果
// Benchmark 名字 - CPU 循环次数 平均每次执行时间
BenchmarkFmt-4 3000000 554 ns/op
BenchmarkPlus-4 2000000000 0.36 ns/op
结论: 0.36 更快一点
一些优化小点
-
在for循环中, ++i要比i++快, for逐渐减小要比逐渐增加快
-
使用 "+" 比使用fmt.Sprintf() 快
-
使用 strconv 包转换 要比 fmt.Sprintf 快
-
使用 strings.Join() 比 "+" 快
-
使用string.Join() 比 bytes.Buffer() 快
-
指定cap的slice 比不指定的快,指定的cap的map比不指定的快。slice 要比使用map快。
string 和 []byte
- 如果可以的话,尽量用多[]byte,少用string
- 尽可能少地在两者之间做转换
后续继续补充
参考
Go 语言测试(Test)、性能测试(Benchmark) 学习笔记
PS: 觉得不错的请点个赞吧!! (ง •̀_•́)ง