funcAdd(str string)int { // This code is to ensure that it takes up more CPU to ensure better debugging for i := 0; i < 10000000000; i++ { if i%100000000 == 0 { log.Printf("add\n") } } data := []byte(str) dataList = append(dataList, string(data)) returnlen(dataList) }
执行 go run main.go 之后,可以通过
http://localhost:6060/debug/pprof/ 进入 pprof
http服务。
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.
这里值得一提的是
profile,它会在经过一段时间的分析后生成一个报告,这个报告可以基于
go tool pprof 打开。
interactive terminal
CPU profiling
在命令行执行
1
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=60
funcAdd(str string)int { // This code is to ensure that it takes up more CPU to ensure better debugging for i := 0; i < 10000000000; i++ { if i%100000000 == 0 { log.Printf("add\n") } } data := []byte(str) dataList = append(dataList, string(data)) returnlen(dataList) }
add_test.go
1 2 3 4 5 6 7 8 9
package add
import"testing"
funcBenchmarkAdd(b *testing.B) { for i := 0; i < b.N; i++ { Add("go-programming-tour-book") } }
# cpu profile go test -bench=. -cpuprofile=cpu.profile
# memory profile go test -bench=. -memprofile=mem.profile
delve
Delve aims to be a very simple and powerful tool, but can be
confusing if you're not used to using a source level debugger in a
compiled language. This document will provide all the information you
need to get started debugging your Go programs.
#0 0x00000000004666e0 in _rt0_amd64_linux # at /usr/local/go/src/runtime/rt0_linux_amd64.s:8 #1 0x0000000000000000 in ??? # at :0 # error: NULL address
goroutine和goroutines
goroutine相关的命令有两条:
goroutines : List program goroutines.
goroutine : Shows or changes current goroutine
frame
frame 可以设置当前frame,或者指定后续的
command 在指定的 frame 上执行。
1 2 3 4 5 6 7
Set the current frame, or execute command on a different frame.
frame <m> frame <m> <command>
The first form sets frame used by subsequent commands such as "print" or "set". The second form runs the command on the given frame.
list
list 显示源代码,并且可以指定 goroutine 和 frame
1 2 3 4 5
Show source code.
[goroutine <n>] [frame <m>] list [<locspec>]
Show source around current point or provided locspec.