-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpq_test.go
134 lines (114 loc) · 2.31 KB
/
pq_test.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package pq
import (
"testing"
"time"
"sync/atomic"
"runtime"
"math/rand"
)
var inc int64
type testtask struct {
p int
}
func (tt testtask) Run() (err error) {
sleep()
return
}
func (tt testtask) Priority() int {
return tt.p
}
func sleep() (err error) {
time.Sleep(time.Second / 2)
atomic.AddInt64(&inc, 1)
return
}
func finc() (err error) {
atomic.AddInt64(&inc, 1)
return
}
func TestTask(t *testing.T) {
n := 10
q := new(Queue)
if err := q.Start(n); err != nil {
t.Errorf("Can't start queue: %v", err)
return
}
defer q.Stop()
st := time.Now()
for i := 0; i < n; i++ {
if err := q.AddFunc(sleep, 10); err != nil {
t.Errorf("Can't add task: %v", err)
}
}
// add last and wait
if err := q.WaitFunc(sleep, 0); err != nil {
t.Errorf("Can't add task: %v", err)
}
stop := time.Since(st)
if int(stop / time.Second) != 1 {
t.Errorf("Unexpected stop time: %v", stop)
}
if int(inc) != n+1 {
t.Errorf("Unexpected inc: %v", inc)
}
}
func TestGroup(t *testing.T) {
inc = 0
n := 10
q := new(Queue)
if err := q.Start(n); err != nil {
t.Errorf("Can't start queue: %v", err)
return
}
defer q.Stop()
st := time.Now()
tasks := make([]Task, n*2)
for i := 0; i < n*2; i++ {
tasks[i] = testtask{1}
}
// add last and wait
if err := q.WaitGroup(tasks); err != nil {
t.Errorf("Can't add tasks: %v", err)
}
stop := time.Since(st)
if int(stop / time.Second) != 1 {
t.Errorf("Unexpected stop time: %v", stop)
}
if int(inc) != n*2 {
t.Errorf("Unexpected inc: %v", inc)
}
}
func BenchmarkTaskSingleThread1(b *testing.B) {
benchTask(b, 1, 1, false)
}
func BenchmarkTaskSingleThread10(b *testing.B) {
benchTask(b, 10, 1, false)
}
func BenchmarkTaskMultiThread1(b *testing.B) {
benchTask(b, 1, runtime.NumCPU(), false)
}
func BenchmarkTaskMultiThread10(b *testing.B) {
benchTask(b, 10, runtime.NumCPU(), false)
}
func BenchmarkTaskMultiThread30(b *testing.B) {
benchTask(b, 30, runtime.NumCPU(), false)
}
func BenchmarkTaskMultiThread30RandPriority(b *testing.B) {
benchTask(b, 30, runtime.NumCPU(), true)
}
func benchTask(b *testing.B, w, c int, r bool) {
runtime.GOMAXPROCS(c)
q := new(Queue)
q.Start(w)
b.ResetTimer()
for i := 0; i < b.N; i++ {
p := 0
if r {
p = rand.Intn(10)
}
q.AddFunc(finc, p)
}
q.WaitFunc(finc, -1)
b.StopTimer()
defer q.Stop()
}