golang的pprof包

依赖

go提供两个pprof包

  1. net/http/pprof
  2. runtime/pprof
    两个包应用场景存在不同,从前缀即可得知。

示例

1.代码

package main

import (
	"fmt"
	"net/http"
	_"net/http/pprof"//注意下划线
)

func SayHello(w http.ResponseWriter, req *http.Request) {
    w.Write([]byte("Hello"))
}

func main() {
	go func() {
		fmt.Println("pprof start...")
		fmt.Println(http.ListenAndServe(":9998", nil))
	}()

	mux := http.NewServeMux()
	mux.HandleFunc("/", SayHello)

	err := http.ListenAndServe(":9999", mux)
	if err != nil {
		log.Error("ListenAndServe: ", err)
	}
}

2. 查看

浏览器中打开

http://host:9998/debug/pprof/

可以看到如下页面,点击对应链接查看即可

/debug/pprof/

Types of profiles available:
Count	Profile
3	allocs
0	block
0	cmdline
7	goroutine
3	heap
0	mutex
0	profile
8	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.

更多功能参考:
https://blog.golang.org/profiling-go-programs

猜你喜欢

转载自blog.csdn.net/my_live_123/article/details/88877400