一、准备
package main
import (
"encoding/json"
"fmt"
"net/http"
_ "net/http/pprof"
"time"
)
func main() {
go func() {
for {
LocalTz()
doSomething([]byte(`{"a": 1, "b": 2, "c": 3}`))
}
}()
fmt.Println("start api server...")
panic(http.ListenAndServe(":8080", nil))
}
func doSomething(s []byte) {
var m map[string]interface{}
err := json.Unmarshal(s, &m)
if err != nil {
panic(err)
}
s1 := make([]string, 0)
s2 := ""
for i := 0; i < 100; i++ {
s1 = append(s1, string(s))
s2 += string(s)
}
}
func LocalTz() *time.Location {
tz, _ := time.LoadLocation("Asia/Shanghai")
return tz
}
在你启动http server的地方直接加入导入: _ "net/http/pprof"
然后运行程序后,直接访问: http://127.0.0.1:8080/debug/pprof/
, 可以看到go运行的信息:
/debug/pprof/
Types of profiles available:
Count Profile
55 allocs
0 block
0 cmdline
4 goroutine
55 heap
0 mutex
0 profile
10 threadcreate
0 trace
full goroutine stack dump
Profile Descriptions:
allocs: A sampling of all past memory allocations
block: Stack traces that led to blocking on synchronization primitives
cmdline: The command line invocation of the current program
goroutine: Stack traces of all current goroutines
heap: A sampling of memory allocations of live objects. You can specify the gc GET parameter to run GC before taking the heap sample.
mutex: Stack traces of holders of contended mutexes
profile: CPU profile. You can specify the duration in the seconds GET parameter. After you get the profile file, use the go tool pprof command to investigate the profile.
threadcreate: Stack traces that led to the creation of new OS threads
trace: A trace of execution of the current program. You can specify the duration in the seconds GET parameter. After you get the trace file, use the go tool trace command to investigate the trace.
二、使用火焰图
2.1 获取cpuprofile
获取最近10秒程序运行的cpuprofile, -seconds参数不填默认为30。
go tool pprof -seconds 10 http://127.0.0.1:8080/debug/pprof/profile
等10s后会生成一个: pprof.samples.cpu.001.pb.gz
文件
2.2 生成火焰图
go tool pprof -http=:8081 ~/pprof/pprof.samples.cpu.001.pb.gz
其中-http=:8081
会启动一个http服务,端口为8081,然后浏览器会弹出此文件的图解:
三、其它
报错则需要安装 yum install graphviz -y
(centos)
[root@VM-24-6-centos goProject]# go tool pprof -http=0.0.0.0:8123 /root/pprof/pprof.main.samples.cpu.001.pb.gz
Serving web UI on http://0.0.0.0:8123
http://0.0.0.0:8123
Failed to execute dot. Is Graphviz installed?
exec: "dot": executable file not found in $PATH
Failed to execute dot. Is Graphviz installed?
exec: "dot": executable file not found in $PATH
...