-
Notifications
You must be signed in to change notification settings - Fork 41
/
profiling.go
51 lines (47 loc) · 1.33 KB
/
profiling.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
package main
import (
"fmt"
"log"
"os"
"runtime"
"runtime/pprof"
"time"
)
// Write a heap profile to the given file.
func createHeapProfile(filename string) {
f, err := os.Create(filename)
if err != nil {
log.Fatal("could not create memory profile: ", err)
}
defer f.Close() // error handling omitted for example
if err := pprof.WriteHeapProfile(f); err != nil {
log.Fatal("could not write memory profile: ", err)
}
}
// Write a memory allocation profile to the given file.
func createAllocProfile(filename string) {
f, err := os.Create(filename)
if err != nil {
log.Fatal("could not create alloc profile: ", err)
}
defer f.Close() // error handling omitted for example
if err := pprof.Lookup("allocs").WriteTo(f, 0); err != nil {
log.Fatal("could not write alloc profile: ", err)
}
}
// Start a goroutine to periodically write memory profiles.
func startMemoryProfile(prefix string) {
t := 0
log.Println("Starting memory profiling:", prefix)
for {
filename := fmt.Sprintf("%s-heap-%03d", prefix, t)
runtime.GC() // get up-to-date statistics (according to docs)
createHeapProfile(filename)
log.Println("Wrote memory heap profile:", filename)
filename = fmt.Sprintf("%s-allocs-%03d", prefix, t)
log.Println("Wrote memory allocs profile:", filename)
createAllocProfile(filename)
time.Sleep(30 * time.Second)
t++
}
}