~adnano/adnano.co

ref: 50c3d6bd7b90317324b26d01195bdc94cbf9a29a adnano.co/content/2020-07-11-profiling-go-code.gmi -rw-r--r-- 1.4 KiB
50c3d6bdAdnan Maolood Add missing templates 3 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# Profiling Go code

Profiling a Go program is relatively simple. First we have to import "runtime/pprof" and add some code:

```go
func main() {
	// CPU profile
	if path := os.Getenv("CPUPROFILE"); path != "" {
		f, err := os.Create(path)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	// ... (Your code here)

	// Memory profile
	if path := os.Getenv("MEMPROFILE"); path != "" {
		f, err := os.Create(path)
		if err != nil {
			log.Fatal(err)
		}
		pprof.WriteHeapProfile(f)
		f.Close()
	}
}
```

This code enables CPU and memory profiling if the CPUPROFILE and MEMPROFILE environment variables are set. It will then write the profile results to the path provided in the respective environment variable.

For example, the following writes the results of a CPU profile to "example.cpuprof":

```shell
# CPU profile
env CPUPROFILE=example.cpuprof go run example
```

And the following writes the results of a memory profile to "example.memprof":

```shell
# Memory profile
env MEMPROFILE=example.memprof go run example
```

We can then view the results with "go tool pprof". The following command generates a graph and opens it in your web browser:

```shell
go tool pprof -web example.memprof
```

Note that you need to have "graphviz" installed to render the graph.

For more information, see:
=> https://blog.golang.org/pprof Profiling Go Programs