This is a creation in Article, where the information may have evolved or changed.
Profile
Profile is timed sampling, collecting CPU, memory and other information, and then give performance optimization guidance, Golang official provided Golang own performance analysis tool usage, also gave the guidance, the official introduction
Environment
Golang Environment, Graphviz
Generate Profile method
Golang currently provides 3 profiles, CPU profiles, memery profiles, blocking profile, two ways to generate these profiles, one is to use net/http/pprof packages, One is the need to write your own code, the following separate introduction
1. Net/http/pprof method
This method is very very simple, just need to introduce the NET/HTTP/PPROF package on the page can be viewed
package mainimport ( "fmt" "log" "net/http" _ "net/http/pprof")func main() { go func() { for { fmt.Println("hello world") } }() log.Fatal(http.ListenAndServe("0.0.0.0:8080", nil))}
Http://127.0.0.1:8080/debug/pprof View overall information
Http://127.0.0.1:8080/debug/pprof/profile can download CPU profile to observe the analysis
Enter profile from terminal for detailed analysis
Go Tool pprof Http://localhost:6060/debug/pprof/profile
Go Tool pprof Http://localhost:6060/debug/pprof/heap
Go Tool pprof Http://localhost:6060/debug/pprof/block
- How to write code
func main() { cpuf, err := os.Create("cpu_profile") if err != nil { log.Fatal(err) } pprof.StartCPUProfile(cpuf) defer pprof.StopCPUProfile() ctx, _ := context.WithTimeout(context.Background(), time.Second*5) test(ctx) time.Sleep(time.Second * 3) memf, err := os.Create("mem_profile") if err != nil { log.Fatal("could not create memory profile: ", err) } if err := pprof.WriteHeapProfile(memf); err != nil { log.Fatal("could not write memory profile: ", err) } memf.Close()}func test(c context.Context) { i := 0 j := 0 go func() { m := map[int]int{} for { i++ m[i] = i } }() go func() { m := map[int]int{} for { j++ m[i] = i } }() select { case <-c.Done(): fmt.Println("done, i", i, "j", j) return }}
Generates two profiles, one for the CPU and one for the memory. Enter the Proflie method
Go tool pprof Main profile
Main represents a binary file, which is a compiled executable file.
Profile is the profile generated above, can be cpu_profile, or it can be mem_profile
For Cpu_profile, it's time to start counting when the code starts.
Mem_profile part of the code if the code at the beginning of the location is not statistical, you need to find a better location
How to analyze Profile
1. Enter profile according to the method described above (Go tool pprof)
2. View Profile
After entering the profile, you can use the Help command to see which commands are available, use them according to instructions, common commands TopN, list, and so on, or you can use Web commands to draw a graphical analysis of what the browser can see