-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathstopwatch.go
116 lines (94 loc) · 2.46 KB
/
stopwatch.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
package timeutils
import (
"fmt"
"sort"
"strings"
"sync"
"time"
"github.com/golangci/golangci-lint/pkg/logutils"
)
const noStagesText = "no stages"
type Stopwatch struct {
name string
startedAt time.Time
log logutils.Log
stages map[string]time.Duration
mu sync.Mutex
}
func NewStopwatch(name string, log logutils.Log) *Stopwatch {
return &Stopwatch{
name: name,
startedAt: time.Now(),
stages: map[string]time.Duration{},
log: log,
}
}
type stageDuration struct {
name string
d time.Duration
}
func (s *Stopwatch) stageDurationsSorted() []stageDuration {
stageDurations := make([]stageDuration, 0, len(s.stages))
for n, d := range s.stages {
stageDurations = append(stageDurations, stageDuration{
name: n,
d: d,
})
}
sort.Slice(stageDurations, func(i, j int) bool {
return stageDurations[i].d > stageDurations[j].d
})
return stageDurations
}
func (s *Stopwatch) sprintStages() string {
if len(s.stages) == 0 {
return noStagesText
}
stageDurations := s.stageDurationsSorted()
stagesStrings := make([]string, 0, len(stageDurations))
for _, s := range stageDurations {
stagesStrings = append(stagesStrings, fmt.Sprintf("%s: %s", s.name, s.d))
}
return fmt.Sprintf("stages: %s", strings.Join(stagesStrings, ", "))
}
func (s *Stopwatch) sprintTopStages(n int) string {
if len(s.stages) == 0 {
return noStagesText
}
stageDurations := s.stageDurationsSorted()
stagesStrings := []string{}
for i := 0; i < len(stageDurations) && i < n; i++ {
s := stageDurations[i]
stagesStrings = append(stagesStrings, fmt.Sprintf("%s: %s", s.name, s.d))
}
return fmt.Sprintf("top %d stages: %s", n, strings.Join(stagesStrings, ", "))
}
func (s *Stopwatch) Print() {
p := fmt.Sprintf("%s took %s", s.name, time.Since(s.startedAt))
if len(s.stages) == 0 {
s.log.Infof("%s", p)
return
}
s.log.Infof("%s with %s", p, s.sprintStages())
}
func (s *Stopwatch) PrintStages() {
var stagesDuration time.Duration
for _, s := range s.stages {
stagesDuration += s
}
s.log.Infof("%s took %s with %s", s.name, stagesDuration, s.sprintStages())
}
func (s *Stopwatch) PrintTopStages(n int) {
var stagesDuration time.Duration
for _, s := range s.stages {
stagesDuration += s
}
s.log.Infof("%s took %s with %s", s.name, stagesDuration, s.sprintTopStages(n))
}
func (s *Stopwatch) TrackStage(name string, f func()) {
startedAt := time.Now()
f()
s.mu.Lock()
s.stages[name] += time.Since(startedAt)
s.mu.Unlock()
}