/
main.go
76 lines (63 loc) · 1.16 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
package main
import (
"os"
"runtime"
"runtime/pprof"
"sync"
"time"
)
var foo []string
func main() {
demonstrateSleep()
f, err := os.Create("block.pb.gz")
if err != nil {
panic(err)
}
defer f.Close()
if err := pprof.Lookup("block").WriteTo(f, 0); err != nil {
panic(err)
}
}
func demonstrateSleep() {
runtime.SetBlockProfileRate(1)
<-time.After(time.Millisecond)
}
func demonstrateSelect() {
runtime.SetBlockProfileRate(1)
ch1 := make(chan struct{}, 0)
ch2 := make(chan struct{}, 1)
ch3 := make(chan struct{}, 0)
go func() {
ch2 <- struct{}{}
}()
time.Sleep(20 * time.Millisecond)
select {
case <-ch1:
case <-ch2:
case <-ch3:
}
}
func demonstrateSampling() {
runtime.SetBlockProfileRate(int(40 * time.Microsecond.Nanoseconds()))
for i := 0; i < 10000; i++ {
blockMutex(10 * time.Microsecond)
}
}
func blockMutex(d time.Duration) {
m := &sync.Mutex{}
m.Lock()
go func() {
spinSleep(d)
m.Unlock()
}()
m.Lock()
}
// spinSleep is a more accurate version of time.Sleep() for short sleep
// durations. Accuracy seems to be ~35ns.
func spinSleep(d time.Duration) {
start := time.Now()
n := 0
for time.Since(start) < d {
n++
}
}