🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
这一点主要使用pprof来实现。开启pprof也特别简单,用net/http/pprof包可以快速实现。只需要在之前的代码中加下面三行就可以: ~~~ package main import ( "log" "net/http" _ "net/http/pprof" ) func main() { log.Println(http.ListenAndServe("localhost:8081", nil)) } ~~~ 在程序启动之后,只需要在命令行或者浏览器输入以下命令即可: ~~~ go tool pprof http://127.0.0.1:8081/debug/pprof/heap //查看堆的使用,即内存使用情况 go tool pprof http://127.0.0.1:8081/debug/pprof/profile //查看cpu耗时,会详细列出每个函数的耗时 go tool pprof http://127.0.0.1:8081/debug/pprof/goroutine //当前在运行的goroutine情况以及总数 ~~~ 可以看下profile的输出信息, flat代表单个函数的运行时间,而cum则是累加的时间,也会包括这个函数下面的子函数的累加时间,所以main.main肯定是100%: ~~~ Showing nodes accounting for 1485.59kB, 100% of 1485.59kB total Showing top 10 nodes out of 14 flat flat% sum% cum cum% 902.59kB 60.76% 60.76% 1485.59kB 100% compress/flate.NewWriter /usr/local/go/src/compress/flate/deflate.go 583.01kB 39.24% 100% 583.01kB 39.24% compress/flate.newDeflateFast /usr/local/go/src/compress/flate/deflatefast.go (inline) 0 0% 100% 583.01kB 39.24% compress/flate.(*compressor).init /usr/local/go/src/compress/flate/deflate.go 0 0% 100% 1485.59kB 100% compress/gzip.(*Writer).Write /usr/local/go/src/compress/gzip/gzip.go 0 0% 100% 1485.59kB 100% net/http.(*ServeMux).ServeHTTP /usr/local/go/src/net/http/server.go 0 0% 100% 1485.59kB 100% net/http.(*conn).serve /usr/local/go/src/net/http/server.go 0 0% 100% 1485.59kB 100% net/http.HandlerFunc.ServeHTTP /usr/local/go/src/net/http/server.go 0 0% 100% 1485.59kB 100% net/http.serverHandler.ServeHTTP /usr/local/go/src/net/http/server.go 0 0% 100% 1485.59kB 100% net/http/pprof.Index /usr/local/go/src/net/http/pprof/pprof.go 0 0% 100% 1485.59kB 100% net/http/pprof.handler.ServeHTTP /usr/local/go/src/net/http/pprof/pprof.go ~~~ 如果想看具体的图示的话,可以使用png命令将结果存成图片看(png > "路径"),比如: ~~~ (pprof) png > /Users/liupengjie/Downloads/heap.png Generating report in /Users/liupengjie/Downloads/heap.png ~~~ 可以看到生成图片的样子, 有具体的箭头以及每个函数占用的时间或者内存。