ふわふわ時間

0%

GO 进程资源占用分析

使用 pprof 和 graphviz 分析进程内存分配,CPU 耗时等信息。


当我们想分析自己写的代码中内存分配主要发生在哪或者哪些语句比较耗时时,可以使用 pprof 帮我们记录这些信息。只需要在代码中嵌入一个 goroutine 即可:

1
2
3
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
  1. 可以通过浏览器打开 http://localhost:6060/debug/pprof/ 即可查看相关信息

    • 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
    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

  3. 在命令行中也可使用 graphviz 将获得的信息以图的形式展现 png > filename.png