性能分析工具,可以查看函数调用的耗时,进行性能瓶颈分析。
- 命令行程序的性能分析
package main
import (
"context"
"github.com/go-redis/redis/v8"
"encoding/json"
"log"
"os"
"runtime/pprof"
)
type Resource struct {
Type string `json:"type"`
Content string `json:content`
}
type Rule struct {
Id int `json:"id"`
Type string `json:"type"`
Keyword string `json:"keyword"`
Priority string `json:"priority"`
Resource *Resource `json:"resource"`
}
func getRule() *[]Rule {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "ip:2091",
Password: "",
DB: 0,
})
rule := &[]Rule{}
val, err := rdb.Get(ctx, "weixin_xiaohua_admin_rule").Result()
if err != nil {
log.Fatal(err)
return rule
}
for i:=0; i<50; i++ {
err = json.Unmarshal([]byte(val), rule)
if err != nil {
log.Fatal(err)
return rule
}
}
return rule
}
func main() {
f,err := os.Create("cpu-profile.prof")
if err!=nil {
log.Fatal(err)
return
}
//开启性能分析
pprof.StartCPUProfile(f)
//你的业务代码
getRule()
pprof.StopCPUProfile()
}
go build -o json json.go
./json
go tool pprof json cpu-profile.prof
在打开的pprof终端中输入web命令,可以调起本地浏览器展示svg结果
- web服务的性能分析 a. 如果没有用到gin等web框架
package main
import (
"encoding/json"
"fmt"
"net/http"
_ "net/http/pprof" //这里会注册路由,请求处理函数中调用cpu profile等
)
type Student struct {
Name string
Age int
Class *Class
}
type Class struct {
Name string
}
func main() {
//你的业务服务代码
//6060端口用于打开性能分析页面,可以本地货浏览器查看
http.ListenAndServe("0.0.0.0:6060", nil)
}
//压测请求的同时,访问http://ip:6060/debug/pprof/profile 会下载profile文件
go tool pprof ./main profile
//或者
go tool pprof ./main http://ip:6060/debug/pprof/profile
//输入web命令调起本地浏览器打开svg
b. 如果你的服务用的gin框架
import "github.com/gin-contrib/pprof"
r := gin.New()
//debug模式下开启pprof
if runMode=="debug" {
pprof.Register(r)
}
//启动服务器以后,会有/debug/prof,打开http://ip:port/debug/prof可以查看
go tool pprof http://ip:port/debug/pprof/goroutine?second=20
//在交互式终端,输入web命令可以调起本地浏览器
web
//help命令可以查看可用的命令列表
通过/debug/prof/trace可以查看trace分析。