forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 4
/
continuous_meter.go
79 lines (65 loc) · 1.78 KB
/
continuous_meter.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
// Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package meter
import (
"math"
"time"
)
var (
convertEToBase2 = math.Log(2)
_ Factory = (*ContinuousFactory)(nil)
_ Meter = (*continuousMeter)(nil)
)
// ContinuousFactory implements the Factory interface by returning a continuous
// time meter.
type ContinuousFactory struct{}
func (ContinuousFactory) New(halflife time.Duration) Meter {
return NewMeter(halflife)
}
type continuousMeter struct {
halflife float64
value float64
numCoresRunning float64
lastUpdated time.Time
}
// NewMeter returns a new Meter with the provided halflife
func NewMeter(halflife time.Duration) Meter {
return &continuousMeter{
halflife: float64(halflife) / convertEToBase2,
}
}
func (a *continuousMeter) Inc(now time.Time, numCores float64) {
a.Read(now)
a.numCoresRunning += numCores
}
func (a *continuousMeter) Dec(now time.Time, numCores float64) {
a.Read(now)
a.numCoresRunning -= numCores
}
func (a *continuousMeter) Read(now time.Time) float64 {
timeSincePreviousUpdate := a.lastUpdated.Sub(now)
if timeSincePreviousUpdate >= 0 {
return a.value
}
a.lastUpdated = now
factor := math.Exp(float64(timeSincePreviousUpdate) / a.halflife)
a.value *= factor
a.value += a.numCoresRunning * (1 - factor)
return a.value
}
func (a *continuousMeter) TimeUntil(now time.Time, value float64) time.Duration {
currentValue := a.Read(now)
if currentValue <= value {
return time.Duration(0)
}
// Note that [factor] >= 1
factor := currentValue / value
// Note that [numHalfLives] >= 0
numHalflives := math.Log(factor)
duration := numHalflives * a.halflife
// Overflow protection
if duration > math.MaxInt64 {
return time.Duration(math.MaxInt64)
}
return time.Duration(duration)
}