go中提供了pprof包来做代码的性能监控,在两个地方有包:
使用 net/http/pprof 做WEB服务器的性能监控
import (
_ “net/http/pprof”
)
然后就可以在浏览器中使用http://localhost:port/debug/pprof/ 直接看到当前web服务的状态,包括CPU占用情况和内存使用情况等。
在 main 方法中增加func main() { go func() { http.ListenAndServe("localhost:8082", nil) }() }
可以在终端执行
go tool pprof –text http://localhost:port/debug/pprof/heap 查看分析数据
下面是我的测试样例:
Fetching profile from http://localhost:port/debug/pprof/heap Saved profile in /root/pprof/pprof.localhost:port.inuse_objects.inuse_space.274.pb.gz 20512.19kB of 20512.19kB total ( 100%) Dropped 68 nodes (cum <= 102.56kB) flat flat% sum% cum cum% 20000kB 97.50% 97.50% 20000kB 97.50% github.com/gorilla/websocket.newConn 512.19kB 2.50% 100% 512.19kB 2.50% runtime.malg 0 0% 100% 20000kB 97.50% github.com/gorilla/websocket.(*Upgrader).Upgrade 0 0% 100% 20000kB 97.50% github.com/gorilla/websocket.Upgrade 0 0% 100% 20000kB 97.50% main.wsHandler 0 0% 100% 20000kB 97.50% net/http.(*ServeMux).ServeHTTP 0 0% 100% 20000kB 97.50% net/http.(*conn).serve 0 0% 100% 20000kB 97.50% net/http.HandlerFunc.ServeHTTP 0 0% 100% 20000kB 97.50% net/http.serverHandler.ServeHTTP 0 0% 100% 20000kB 97.50% runtime.goexit 0 0% 100% 512.19kB 2.50% runtime.mcommoninit 0 0% 100% 512.19kB 2.50% runtime.mpreinit 0 0% 100% 512.19kB 2.50% runtime.rt0_go 0 0% 100% 512.19kB 2.50% runtime.schedinit