使用 pprof 和 graphviz 分析进程内存分配,CPU 耗时等信息。
当我们想分析自己写的代码中内存分配主要发生在哪或者哪些语句比较耗时时,可以使用 pprof 帮我们记录这些信息。只需要在代码中嵌入一个 goroutine 即可:
|
|
-
可以通过浏览器打开
http://localhost:6060/debug/pprof/
即可查看相关信息allocs
: A sampling of all past memory allocationsblock
: Stack traces that led to blocking on synchronization primitivescmdline
: The command line invocation of the current programgoroutine
: Stack traces of all current goroutinesheap
: 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 mutexesprofile
: 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 threadstrace
: 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.
-
也可通过命令行查看
1 2 3 4 5
// 查看堆内内存分配情况 go tool pprof http://localhost:6060/debug/pprof/heap // 查看 30 秒内 CPU 耗时信息 go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
-
在命令行中也可使用 graphviz 将获得的信息以图的形式展现
png > filename.png