Author: NING Liang

I. Common analysis commands and tools

  • pprof
  • go tool [xxx]
  • go test
  • delve
  • go race
  • gdb

II. Parameter passing during program compilation

1, gcflags

// Go build -gcflags="-m"; // Go build -gcflags="-m";

For example, -N disables compilation optimization, -L disallows inlining, -M prints compilation optimization policies (including escape conditions and whether functions are inlined, and whether variables are allocated on the heap or stack), and -S prints assembly.

If parameters need to be passed only when compiling a specific package, the format should follow the “package name = parameter list”, such as Go Build-GCFlags =’log= -n-l ‘main.go

2, ldflags

Go Build uses -ldflags to pass parameters to the Go linker, which are actually parameters for the Go Tool link. You can use Go Tool link –help to see the available parameters.

-x is often used to specify parameters such as version number that are determined at compile time. For example, we define var buildVer string in our code and assign it at compile time with go build-ldflags “-x main.buildver =1.0”. Note that -x can only assign values to string variables.

B: Go build-x

You can list all the commands that Go Build triggers, such as toolchains, cross-platform compilation, flags passed to external compilers, linkers, and so on. You can use -x to see all the triggers.

IV. Competitive testing

Use Go Run-Race main.go or Go Build-Race main.go for race detection.

5. GC log

  • Add the system environment variable GODEBUG=’gctrace=1′ before execution to track the printed garbage collector information
  • Use Runtime.ReadMemStats in your code to get the current memory usage of your program
  • Use the pprof tool

For example, goDebug = GCTrace =1 Go Run Main. go // The Go program prints GC information every once in a while.

Six, Pprof

The Go language has built-in tools for getting data about how a program runs, including the following two standard libraries

(1) Runtime/Pprof: Collection of runtime data for analysis; (2) NET/HTTP/Pprof: Collection of runtime data for analysis of service-oriented applications

1. Tool application analysis

(1) CPU analysis
f, err := os.Create(*cpuprofile)
defer pprof.StopCPUProfile()
(2) Memory analysis
f, err := os.Create(*memprofile)

2. Enable PPROF when using NET/HTTP packages

package main

import (
_ "net/http/pprof"

func main() {
//... do something

log.Println(http.ListenAndServe("localhost:8090", nil))

3. Enable PPROF when using GIN

package main

import (

func main() {
app := gin.Default()



7. Access the Web page for analysis results

If you enable Pprof on a native test service, you can usehttp://…The HTTP service:

/debug/pprof/ Types of profiles available: Count Profile 3 allocs 0 block //goroutine 0 cmdline 4 goroutine 0 0 profile 7 threadcreate 0 trace goroutine stack dump 0 trace goroutine stack dump 0 trace goroutine stack dump 0 trace goroutine stack dump 0 trace goroutine stack dump 0 trace goroutine stack dump 0 trace goroutine stack dump 0 trace goroutine stack dump

1. PPROF supports four types of analysis

After Pprof is turned on, the current stack information is collected at regular intervals (by default, 10ms) to obtain the CPU and memory resources occupied by each function, and then the sampled data is analyzed to form a performance analysis report.

CPU-consuming calls. This is usually used to locate the areas of the program that consume computing resources
(2) Memory Profile (Heap Profile) : Memory analysis, commonly used to detect Memory footprint, Memory leaks and other problems. A record of heap memory allocations. By default, the sample is sampled every 512K bytes allocated.
(3) Block Profile: Blocking Analysis, which reports the condition of synchronization primitives causing the blocking, can be used to analyze and find the performance bottleneck of locks. A stack trace of Goroutine blocking events. The default is to sample once every blocking event occurs.
(4) Goroutine Profile: report how goroutines are used, which goroutines are there, and how they are called. Record information about active goroutines, as well as calling relationships. Sample only once at fetch.

2. Pprof visualization

To install Graphviz from brew on a Mac, execute the following command: brew install Graphviz

3. Get the analysis results in the form of local files

You can dump the information to a local file and use the Go Tool to analyze it.

4, debugcharts

A real-time view of the GO program memory, CPU, GC, coroutine and other changes in the visualization tool. Enable in a similar way to Pprof, import first, and then enable port listening.

package main

import (
_ ""

func main() {
//... do something

log.Println(http.ListenAndServe("localhost:8090", nil))

Then open it in your browser:…

5. Third-party tool Prometheus

Prometheus is a Grafana plugin that supports visualization of GO monitoring.

Enable it by introducing packages first:

import (



Then add routing:

http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8090", nil)

Finally, by accesshttp:// the collected index data.

Note: Pprof + Charts + Prometheus can also be enabled on one port at the same time.

Go Tool [XXX] series command

1, Enter Go Tool to view all the built-in [XXX] tool commands

Addr2line API ASM Buildid CGO compile: compile: generate code cover: dist doc fix link Oldlink pack pprof: test2json trace: test2json trace: vet

2, Go Tool nm to view symbol table command

At breakpoint time, if you don’t know the function symbol of the breakpoint, you can use this command to query (the command deals with binary program files). The first column of Go Tool nm./main output is the address, the second column is the type, and the third column is the symbol.

115aa00 T bufio.(*ReadWriter).Available

115aa20 T bufio.(*ReadWriter).Discard

115aa60 T bufio.(*ReadWriter).Flush

115aa80 T bufio.(*ReadWriter).Peek

3, Go tool compile a file

go tool compile -N -l -S main.go

4, Go tool objdump disassembles binaries

Go tool objdump main.o Go tool objdump -s DoFunc main.o Go tool objdump -s DoFunc main.o Go tool objdump -s DoFunc main.o

5, GO Tool PPROF performance index analysis tool

5.1 Command line analysis pattern

go tool pprof http://localhost:8090/debug/p… Analyze the heap, go to command-line mode, and type Web to open it in Web mode (if Graphviz is installed).

Or continue with the command line: type top to see the top 10 memory consuming functions in the program by default, type top 3 to see the top three memory consuming functions in the program. Also, if you’re harvesting a CPU, use the top command to see which functions are using the CPU

(1) The function name is shown in the last column after input top, and the meaning of other contents is as follows:

Flat % : The percentage of time that the current function spent on the CPU sum% : The cumulative percentage of time that the function spent on the CPU cum: The percentage of time that the current function + the called subfunctions spent on the CPU cum% : The percentage of time that the current function + the called subfunctions spent on the CPU

(3) You can type PDF on the command line to generate a visual PDF file. (4) You can type Help on the command line to provide all the commands supported by Pprof

5.2 Web analysis pattern

(1) Go Tool Pprof -HTTP =:1234http://localhost:8090/debug/p…It will open directly on the Web. Or:http://localhost:1234/ui/You can also open it directly, from which you can filter directly to view the Flame Graph. – HTTP means using an interactive Web interface to view the performance information obtained by specifying the available port. The debug/pprof/need to look at indicators (allocs, block, goroutine, heap, etc.). The flame diagram shows the method call stack from top to bottom, and the length represents the CPU time used.

5.3 Go Tool Pprof analysis command
go tool pprof -http=:1234 http://localhost:8090/debug/pprof/goroutine? second=10 go tool pprof --seconds 10 http://localhost:8090/debug/pprof/goroutine

If the application is complex and the generated call graph is very large and looks messy, there are two ways to optimize it: (1) use the Web [FuncName] method, printing only the content related to a certain function. (2) If you run the Go Tool pprof command with the –nodefration parameter, you can ignore the function that uses less memory. For example, if the subfunction is called with no more than 5% CPU, you can ignore it. Do not show it in pictures.

A: Go Test B: Go Test C: Go Test

(1) Essentially, Golang runs a single test by compiling the *_test.go file, compiling it into a binary, and then running the binary

Go test. // Run Go test. Go test. Go test. Go test. Print test name, status (pass or fail), time, log of test cases, etc. Go test-race // Test detection and reporting support Go test-coverprofile =c.out && Go Tool cover-html =c.out // Output a result of the overlay information and can be viewed visually on the browser
(2) Statistical code coverage

Add a -coverprofile parameter to record code coverage when running a single test. For example, go test-coverprofile =coverage.out, go tool cover =coverage.out, go tool cover-func =coverage.out

Ten, Delve

Delve is currently the most friendly Golang debugger, and IDE debugging is simply a call to DLV, such as the one used by Goland. Install DLV: Go Get-U Check the installation version information: DLV Version

Two ways to load a program into the Delve debugger (prior to having go.mod)

1, load the source code for debugging

Execution of DLV DEBUG into command line mode will automatically generate an __debug_bin file in the same directory. This file is generated by source code compilation and is automatically loaded into the debugger. (2) Delve expects to build a single binary file from a single program or project. If there are multiple source files in the directory and each file has its own main function, Delve may throw an error. In this case, you should use the second method below, load the binary file for debugging.

2, load the binary file for debugging

DLV exec./main (1) loads the binaries into the debugger using the DLV exec command. (2) Type help in command line mode to see the available commands. (3) Some commonly used commands:

}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} // Clear all breakpoints // Clear all breakpoints // Clear all breakpoints // Set a command, when a breakpoint is hit C // Continue to run the program, terminate at breakpoints Continue n // Step through the next line of source code, which is equivalent to next. By default, Delve does not debug function calls any further. Stack // Print out the contents of the current stack, see 0, 1, 2, 3... Frame 0 // implements the jump between frames, Print [var_name] print [var_name] print [var_name] print [var_name] print [var_name] print [var_name] print [var_name] print [var_name] print [var_name // Prints the function function function regs // Prints the register information x // which is equal to examineMem, which is used for parsing memory. // print the global variable (package variable); // print the type information; // restart the program and debug it, which is equivalent to restart the program and quit the debugger

Coroutines related

Goroutines (alias: GRS) goroutines (alias: GRS) goroutines (alias: GRS) // Print all threads

Stack related

Deferred // Run the command down // up the stack frame in the deferred function context // Jump to a specific stack (alias: bt) // Print the stack information up // down the stack

Other commands

Print (alias: disassemble) print (alias: disass) print (alias: disass) Ls | l)/source / / / show the source code load command sources / / print source types / / print all types of information

(4) Other commands of DLV

DLV Debug allows you to debug main directly in the main file directory, or in the root directory by specifying the path to the package. DLV: DLV TEST: DLV TEST: DLV ATTACH: DLV ATTACH: Attach to a running process for debugging. DLV CONNECT: Use DLV Connect to connect to the debug server for debugging DLV Trace: Use DLV Trace to trace programs

Go race

1. The GO language provides a GO RACE DETECTOR to perform competitive analysis and discovery. 2, Go run-race main.go is a runtime check, not a compile time check. There is a significant performance overhead associated with using Race, so try not to use this in a production environment.

Twelve, GDB

1, GDB related commands

Info goroutines // Prints all goroutines goroutines ${id} bt // Prints a stack iFace of goroutines // Prints static or dynamic interface types

2. Correlation function of GDB

Len // prints the channels with the four types of length, the cap // prints the channels with the two types of cap dtype // to force the interface to the dynamic type

Scan the code and add friends to pull you into the technical exchange group, add the micro code: sifou