-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathelapsed.go
74 lines (60 loc) · 1.43 KB
/
elapsed.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
package middleware
import (
"context"
"sync"
"time"
"github.com/hmoragrega/workers"
)
// Elapsed is a job middleware that extends the simple counter
// and calculates the total time, average time and the last
// time spent doing the job.
type Elapsed struct {
Counter
total time.Duration
average time.Duration
last time.Duration
mx sync.RWMutex
since func(time.Time) time.Duration
}
// Wrap wraps the inner job to obtain job timing metrics.
func (e *Elapsed) Wrap(next workers.Job) workers.Job {
e.mx.Lock()
if e.since == nil {
e.since = time.Since
}
e.mx.Unlock()
// wrap incoming job with the counter.
next = e.Counter.Wrap(next)
return workers.JobFunc(func(ctx context.Context) error {
start := time.Now()
err := next.Do(ctx)
elapsed := e.since(start)
count := e.Counter.Finished()
e.mx.Lock()
e.last = elapsed
e.total += e.last
e.average = e.total / time.Duration(count)
e.mx.Unlock()
return err
})
}
// Total returns the total time spent executing
// all the job across all the workers.
func (e *Elapsed) Total() time.Duration {
e.mx.RLock()
defer e.mx.RUnlock()
return e.total
}
// Last returns the time spent executing the last job.
func (e *Elapsed) Last() time.Duration {
e.mx.RLock()
defer e.mx.RUnlock()
return e.last
}
// Average returns the average time that takes to
// run the job.
func (e *Elapsed) Average() time.Duration {
e.mx.RLock()
defer e.mx.RUnlock()
return e.average
}