forked from criteo/consul-bench
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstat.go
88 lines (76 loc) · 1.51 KB
/
stat.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
package main
import (
"fmt"
"log"
"sort"
"strings"
"sync"
"time"
)
type Stat struct {
Label string
Value float64
}
func DisplayStats(ch <-chan Stat, done chan struct{}) {
type statC struct {
Stat
Count int
}
var l sync.Mutex
avg := make(map[string]*statC)
entries := make(map[string]Stat)
go func() {
for {
e := <-ch
l.Lock()
entries[e.Label] = e
if _, ok := avg[e.Label]; !ok {
avg[e.Label] = &statC{
Count: 0,
Stat: e,
}
}
avg[e.Label].Value = (avg[e.Label].Value*float64(avg[e.Label].Count) + e.Value) / float64(avg[e.Label].Count+1)
avg[e.Label].Count++
l.Unlock()
}
}()
printLine := func(entries []Stat) {
sort.Slice(entries, func(i, j int) bool {
return strings.Compare(entries[i].Label, entries[j].Label) < 0
})
var s []string
for _, e := range entries {
s = append(s, fmt.Sprintf("%s: %.2f", e.Label, e.Value))
}
log.Println(strings.Join(s, ", "))
}
start := time.Now()
tick := time.Tick(time.Second)
for {
select {
case <-done:
l.Lock()
entriesSlice := []Stat{{
Label: "Runtime (s)",
Value: time.Since(start).Seconds(),
}}
for _, e := range avg {
entriesSlice = append(entriesSlice, e.Stat)
}
log.Println("====== Summary ======")
printLine(entriesSlice)
l.Unlock()
return
case <-tick:
l.Lock()
var entriesSlice []Stat
for _, e := range entries {
entriesSlice = append(entriesSlice, e)
}
printLine(entriesSlice)
entriesSlice = entriesSlice[:0]
l.Unlock()
}
}
}