-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
101 lines (90 loc) · 1.78 KB
/
main.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"os"
"runtime"
"runtime/pprof"
"runtime/trace"
"sort"
"strconv"
"sync"
"time"
)
type ParsedEvent struct {
Type string
Goroutine uint64
Timestamp int64
Stack []StackFrame
}
type StackFrame struct {
Func string
File string
Line int
}
func main() {
// start this so that we get CPU samples added to the trace
// (requires Go >= 1.19)
runtime.SetCPUProfileRate(100)
buf := new(bytes.Buffer)
start := time.Now()
if err := trace.Start(buf); err != nil {
panic(err)
}
var wg sync.WaitGroup
for j := 0; j < 4; j++ {
wg.Add(1)
// just do some work
thingy := make([]int, 1_000_000)
go pprof.Do(context.Background(), pprof.Labels("worker", strconv.Itoa(j)), func(_ context.Context) {
defer wg.Done()
for i := 0; i < 100; i++ {
sort.Ints(thingy)
}
})
}
wg.Wait()
trace.Stop()
stop := time.Now()
if err := os.WriteFile("trace.out", buf.Bytes(), 0660); err != nil {
panic(err)
}
res, err := Parse(buf, "")
if err != nil {
panic(err)
}
var stuff []ParsedEvent
for _, event := range res.Events {
eventType := EventDescriptions[event.Type]
thing := ParsedEvent{
Type: eventType.Name,
Timestamp: event.Ts,
Goroutine: event.G,
}
stk := res.Stacks[event.StkID]
for _, frame := range stk {
thing.Stack = append(thing.Stack, StackFrame{
File: frame.File,
Func: frame.Fn,
Line: frame.Line,
})
}
stuff = append(stuff, thing)
}
buf.Reset()
json.NewEncoder(buf).Encode(stuff)
os.WriteFile("trace.json", buf.Bytes(), 0660)
// PPROF version
f, err := os.Create("trace.pprof")
if err != nil {
panic(err)
}
defer f.Close()
gz := gzip.NewWriter(f)
defer gz.Close()
if err := ToPprof(res, start, stop, gz); err != nil {
panic(err)
}
}