1. The background

After writing the Golang script, I found that it was not running as fast as I expected, so I was not sure which step was time-consuming. Then I imported the Time module by myself and added the recording time to each function. Although I could see the time of each function, I could not determine the reason for the time, so I wanted to find a monitoring tool.

Here are two golang application monitoring tools, trace and pprof tools, which come with Golang and do not need to be installed separately.

2. trace

Turn on trace tracing in your code.

package main

import (
	"os"
	"runtime/trace"
)

func main(a) {
	f, err := os.Create("trace.out")
	iferr ! =nil {
		panic(err)
	}
	defer f.Close()

	err = trace.Start(f)
	iferr ! =nil {
		panic(err)
	}
	defer trace.Stop()

  // Your program here
}
Copy the code

Run the code and generate a trace.out file locally.

$ go tool trace trace.out
Copy the code

This will open a Web browser, and you can view it.

3. pprof

Start pPROF tracing in your code.

import (
	"os"
	"runtime/pprof"
)

func main(a) {
	f, err := os.Create("cpuprofile")
	iferr ! =nil {
		panic(err)
	}
	pprof.StartCPUProfile(f)
	// pprof.writeHeapProfile (f
	defer pprof.StopCPUProfile()

	// Your program here	
}
Copy the code

A CPUProfile file is generated.

$ go tool pprof cpuprofileType: cpu Time: Aug 27, 2020 at 3:22pm (CST) Duration: 43.42s, Total samples = 1.84s (4.24%) Entering interactive mode (type "help" for commands, "O" for options) (pprof) top5-cum # 0% of 1840ms total Showing top 5 nodes out of 117 flat flat% sum% cum cum% 00% 920ms 50.00% DBRsync/base. DBClient. Insert 0 0% 0% 50.00% database/ms SQL 920. (* Stmt.) the Exec 920 ms (inline) 0 0% 0% to 50.00% The database/SQL. (* Stmt). ExecContext 0 0% 0% 50.00% database/ms SQL 920. 920 ms resultFromStatement 0 0% 0% to 50.00% main.(*DBSync).insertDB (pprof)Copy the code

We can also execute the Web command to open the Web page to view.

(pprof) web
failed to execute dot. Is Graphviz installed? Error: exec: "dot": executable file not found in $PATH
Copy the code

This is an error because Graphviz is not installed, so just install it. Download address: https://graphviz.org/download/

If your computer happens to be a Mac, it’s easy to simply install it.

brew install Graphviz
Copy the code

After the installation, restart the monitor. Enter web to open the web page.