-
Notifications
You must be signed in to change notification settings - Fork 0
/
bench.go
83 lines (68 loc) · 1.15 KB
/
bench.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
package main
import (
"fmt"
"sync"
"time"
"flag"
)
var (
maxFlag bool
mode string
)
func init() {
flag.BoolVar(&maxFlag, "max", false, "this help")
flag.StringVar(&mode, "mode", "mutex", "spin & spin_sched & mutex")
}
type handler interface {
add()
}
func execute(locker handler) {
wg := sync.WaitGroup{}
start := time.Now()
g := 200
n := 200000
for index := 0; index < g; index++ {
wg.Add(1)
go func() {
var max int64
for idx := 0; idx < n; idx++ {
if !maxFlag {
locker.add()
continue
}
s := time.Now().UnixNano()
locker.add()
e := time.Now().UnixNano()
c := e - s
if c > max {
max = c
}
}
if maxFlag {
fmt.Println("max in g: ", max/1000/1000, "ms")
}
wg.Done()
}()
}
wg.Wait()
end := time.Now()
cost := end.Sub(start).Nanoseconds()
fmt.Println("avg: ", cost/int64(g*n), "ns")
}
func main() {
flag.Parse()
var locker handler
fmt.Printf("spinlock \n")
locker = &spinLock{
sched: false,
}
execute(locker)
fmt.Printf("\nspinlock sched \n")
locker = &spinLock{
sched: true,
}
execute(locker)
fmt.Printf("\nmutex \n")
locker = &locked{}
execute(locker)
}