-
Notifications
You must be signed in to change notification settings - Fork 15
/
ewma.go
74 lines (57 loc) · 1.69 KB
/
ewma.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 main
import (
"time"
)
// ewma hold the state for an Exponential Weighted Moving Average. For details see:
// https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
// https://github.com/dgryski/trifles/blob/master/ewmaest/ewmaest.go
// https://stackoverflow.com/a/936720
type ewma struct {
total int
completed int
lastCompleted int
start time.Time
last time.Time
perItem time.Duration
α, β float64
}
// newEWMA returns a new EWMA for total items.
//nolint:gomnd
func newEWMA(start time.Time, totalItems int) *ewma {
return &ewma{
start: start,
last: start,
total: totalItems,
α: 0.10,
β: 0.5,
}
}
// Report tells the ewma how many items have been processed.
func (e *ewma) Report(totalCompletedItems int) {
// return early if no new information is being reported
if totalCompletedItems == 0 || e.completed == totalCompletedItems {
return
}
e.completed = totalCompletedItems
lastBlockTime := time.Since(e.last)
e.last = time.Now()
lastItemEstimate := lastBlockTime / time.Duration(e.completed-e.lastCompleted)
e.lastCompleted = e.completed
// use the first measurement directly, without applying α
if e.perItem == 0 {
e.perItem = lastItemEstimate
return
}
e.perItem = time.Duration(e.α*float64(lastItemEstimate)) + time.Duration((1-e.α)*float64(e.perItem))
}
// ETA returns the estimated remaining time.
func (e *ewma) ETA() time.Duration {
remaining := e.total - e.completed
perItem := e.perItem
if e.completed > 0 {
perItem = time.Duration(e.β * float64(e.last.Sub(e.start)) / float64(e.completed))
perItem += time.Duration((1 - e.β) * float64(e.perItem))
}
d := time.Duration(remaining) * perItem
return d
}