golang里面自己自带内存分析,cpu分析,堆分配信息,线程使用状况,goroutine使用状况.这些分析包含在runtime/pprof这个包下面,本文参考的文献:Go性能监控/分析工具:go tool pprofgolang
先看测试代码:web
go func() { fcup, err := os.Create("pprofcpu.log") if err != nil { fmt.Println("can't create file") return } fmem, err := os.Create("pprofmem.log") if err != nil { fmt.Println("can't create file") return } fblock, err := os.Create("pprofblock.log") if err != nil { fmt.Println("can't create file") return } froutinue, err := os.Create("pprofroutinue.log") if err != nil { fmt.Println("can't create file") return } fthread, err := os.Create("pprofthread.log") if err != nil { fmt.Println("can't create file") return } fheap, err := os.Create("pprofheap.log") if err != nil { fmt.Println("can't create file") return } for { pprof.StartCPUProfile(fcup) runtime.MemProfileRate = 512 * 1024 runtime.SetBlockProfileRate(1) time.Sleep(time.Second * 60) pprof.StopCPUProfile() pprof.WriteHeapProfile(fmem) pprof.Lookup("block").WriteTo(fblock, 2) pprof.Lookup("goroutine").WriteTo(froutinue, 2) pprof.Lookup("threadcreate").WriteTo(fthread, 2) pprof.Lookup("heap").WriteTo(fheap, 2) } }()
这个是关于分析工具部分的一段实现代码,主要是将cpu信息,heap信息,goroutinue信息,线程信息,块信息都保存到文件里面.这些接口使用"runtime/pprof"的就够了.在保持文件时,使用方法:WriteTo有两个参数,第一个参数是保存文件的句柄,第二个参数是保持信息的基本,可设置的值分别为0,1,2:浏览器
为 0 时,仅仅输出 pprof(程序)须要的十六进制地址函数
为 1 时,输出时增长函数名和行号,这样无需工具也能够阅读此 profile工具
为 2 时,而且当输出 goroutine profile 时,输出的 goroutine 栈的格式为未 recovered panic 时的格式性能
这样直接使用看起来不是很方便,go还提供了 web的形式,使用会更方便一些. 首先是须要载入包:_ "net/http/pprof"
须要注意的是必须以这样的形式import, 由于这个包其实在带中没有用到,可是在运行的时候会用到,因此若是前面不带"_"的导入,会编译错误. 而后就是须要添加监听的端口:测试
pprofMux := http.DefaultServeMux go func() { http.ListenAndServe("localhost:8081", pprofMux) }()
若是你的项目自己就是go 的web项目,那么就是要添加两个监听的端口,有一个是独立运行专门用来显示分析数据的.当程序运行以后在浏览器里面输入以下: http://localhost:8081/debug/pprof
线程
就能够看到想要的页面了:debug
/debug/pprof/ Types of profiles available: Count Profile 78 allocs 0 block 0 cmdline 1043 goroutine 78 heap 0 mutex 0 profile 17 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.