misc.py 1.8 KB
Newer Older
1
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
W
WuHaobo 已提交
2
#
3 4 5
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
W
WuHaobo 已提交
6 7 8
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
9 10 11 12 13
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
W
WuHaobo 已提交
14 15 16 17 18 19 20 21 22

__all__ = ['AverageMeter']


class AverageMeter(object):
    """
    Computes and stores the average and current value
    """

L
littletomatodonkey 已提交
23
    def __init__(self, name='', fmt='f', postfix="", need_avg=True):
W
WuHaobo 已提交
24 25
        self.name = name
        self.fmt = fmt
L
littletomatodonkey 已提交
26
        self.postfix = postfix
27
        self.need_avg = need_avg
W
WuHaobo 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
        self.reset()

    def reset(self):
        """ reset """
        self.val = 0
        self.avg = 0
        self.sum = 0
        self.count = 0

    def update(self, val, n=1):
        """ update """
        self.val = val
        self.sum += val * n
        self.count += n
        self.avg = self.sum / self.count

44 45
    @property
    def total(self):
L
littletomatodonkey 已提交
46 47
        return '{self.name}_sum: {self.sum:{self.fmt}}{self.postfix}'.format(
            self=self)
48

49 50
    @property
    def total_minute(self):
L
littletomatodonkey 已提交
51
        return '{self.name} {s:{self.fmt}}{self.postfix} min'.format(
52 53
            s=self.sum / 60, self=self)

54 55
    @property
    def mean(self):
L
littletomatodonkey 已提交
56
        return '{self.name}: {self.avg:{self.fmt}}{self.postfix}'.format(
57 58 59 60
            self=self) if self.need_avg else ''

    @property
    def value(self):
L
littletomatodonkey 已提交
61 62
        return '{self.name}: {self.val:{self.fmt}}{self.postfix}'.format(
            self=self)