1. 引入pprof包, 并监听端口, 为了测试性能, 这里f1方法每秒会创建1个长度100w的数组
package main
import (
"fmt"
"log"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
// 性能分析
go pprof()
f1()
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT)
<-ch
}
func f1() {
go func() {
tick := time.Tick(time.Second)
for {
select {
case now := <-tick:
// 每秒创建一个长度为100w的数组
_ = make([]int, 1000000)
fmt.Println("now", now)
}
}
}()
}
func pprof() {
// 启动HTTP服务器,监听在6060端口(或你选择的任何端口)
log.Println(http.ListenAndServe(":6060", nil))
}
2. 启动进程
go run main.go
3. 网页打开http://localhost:6060/debug/pprof/, 页面如下, 点击profile等几十秒会下载到一个profile文件
4. 运行pprof工具, 其中profile就是刚才下载到文件. 这时会自动打开网页http://localhost:8080/ui/, 如下图所示.
go tool pprof -http=localhost:8080 profile
5. 至此就可以进行性能分析了, 用的比较多的火焰图, 更能直观的分析各个方法的耗时.
遇到的问题:
1. graphviz工具下载, 如果是mac, 需要通过brew下载. brew最好国内镜像的. 不然一天都下不来下.
国内brew镜像安装:
/bin/bash -c "$(curl -fsSL https://gitee.com/cunkai/HomebrewCN/raw/master/Homebrew.sh)"