-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathMeter.py
51 lines (41 loc) · 1.25 KB
/
Meter.py
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
from typing import List
class WeightedMeter:
def __init__(self, name: str = None):
self.name = name
self.count = 0
self.sum = 0.0
self.avg = 0.0
self.val = 0.0
def update(self, val: float, num: int = 1):
self.count += num
self.sum += val * num
self.avg = self.sum / self.count
self.val = val
def reset(self, total: float = 0, count: int = 0):
self.count = count
self.sum = total
self.avg = total / max(count, 1)
self.val = total / max(count, 1)
class AverageMeter:
def __init__(self, length: int, name: str = None):
assert length > 0
self.name = name
self.count = 0
self.sum = 0.0
self.current: int = -1
self.history: List[float] = [None] * length
@property
def val(self) -> float:
return self.history[self.current]
@property
def avg(self) -> float:
return self.sum / self.count
def update(self, val: float):
self.current = (self.current + 1) % len(self.history)
self.sum += val
old = self.history[self.current]
if old is None:
self.count += 1
else:
self.sum -= old
self.history[self.current] = val