函数的压测
var keys = []string{}
func init() {
for i:= 0; i<= 1000000; i++ {
keys = append(keys, "/110000001^uuplxammm2958")
}
}
func Testkey(key string) (uid string, aid string) {
r := strings.Split(key, "^")
aid = strings.Replace(r[0], "/", "", 1)
uid = r[1]
return
}
func Testkey1(key string) (uid string, aid string) {
r := strings.Index(key, "^")
if r >= 0 {
aid = key[1:r]
uid = key[r+1:]
}
return
}
func benchmarkTestkey(b *testing.B, f func(string) (string, string), o int) {
defer b.StopTimer()
b.ResetTimer()
for _, key := range keys {
uid, app_id := f(key)
if uid == "" || app_id == "" {
b.Fatalf("Benchmark_Testkey_%d key = %s, uid = %s, app_id = %s", o, key, uid, aid)
}
}
}
func Benchmark_1_Testkey(b *testing.B) {benchmarkTestkey(b, Testkey, 0)}
func Benchmark_2_Testkey(b *testing.B) {benchmarkTestkey(b, Testkey1, 1)}
运行:
go test -bench='Testkey$' ./test/benchmark -benchmem --运行Testkey前缀的压测函数
输出分析文件:
go test -bench='Testkey$' ./test/benchmark -benchmem -test.memprofile mem.out --运行Testkey前缀的压测函数
观测到目录生成
benchmark.test
mem.out
以pprof显示内存性能分析文件:
go tool pprof -http=:1234 benchmark.test mem.out
pprof 即在golang下内置的性能分析工具,一般在性能测试时引入
先安装:graphviz
import "net/http"
import _ "net/http/pprof"
func main() {
// 主函数中添加
http.ListenAndServe("0.0.0.0:9999", nil)
}
执行命令:启动web界面
go tool pprof -http=:1234 http://localhost:9999/debug/pprof/profile(可选其他选项heap,allocs..)
直接读取上述命令生成的资源文件,适用与线上服务器
go tool pprof -http=:1234 pprof.http.alloc_objects.alloc_space.inuse_objects.inuse_space.002.pb.gz
直接生成svg性能分布文件
go tool pprof -svg http://localhost:9999/debug/pprof/heap > heap.svg
web访问:http://localhost:1234 即可观察
具体实现可查看源码,使用该工具可以与http服务共用端口
go get github.com/gin-contrib/pprof
package main
import (
"github.com/gin-contrib/pprof"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
pprof.Register(router)
router.Run(":8080")
}