-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprofile.go
55 lines (51 loc) · 1.21 KB
/
profile.go
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
// Copyright © 2021-2023 The Gomon Project.
package gocore
import (
"context"
"fmt"
"os"
"runtime"
"runtime/pprof"
)
// profile turns on CPU performance or Memory usage profiling of command.
// Profiling can also be enabled via the /debug/pprof endpoint.
func profile(ctx context.Context) {
if Flags.cpuprofile {
if f, err := os.CreateTemp("", "pprof_"); err != nil {
Error("cpuprofile", err).Err()
} else {
go func() {
pprof.StartCPUProfile(f)
<-ctx.Done()
pprof.StopCPUProfile()
cmd, _ := os.Executable()
fmt.Fprintf(os.Stderr,
"CPU profile written to %[1]q.\nUse the following command to evaluate:\n"+
"\033[1;31mgo tool pprof -web %[2]s %[1]s\033[0m\n",
f.Name(),
cmd,
)
f.Close()
}()
}
}
if Flags.memprofile {
if f, err := os.CreateTemp(".", "mprof_"); err != nil {
Error("memprofile", err).Err()
} else {
go func() {
<-ctx.Done()
runtime.GC()
pprof.WriteHeapProfile(f)
cmd, _ := os.Executable()
fmt.Fprintf(os.Stderr,
"Memory profile written to %[1]q.\nUse the following command to evaluate:\n"+
"\033[1;31mgo tool pprof -web %[2]s %[1]s\033[0m\n",
f.Name(),
cmd,
)
f.Close()
}()
}
}
}