misc.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. __all__ = ['AverageMeter']
  15. class AverageMeter(object):
  16. """
  17. Computes and stores the average and current value
  18. """
  19. def __init__(self, name='', fmt='f', postfix="", need_avg=True):
  20. self.name = name
  21. self.fmt = fmt
  22. self.postfix = postfix
  23. self.need_avg = need_avg
  24. self.reset()
  25. def reset(self):
  26. """ reset """
  27. self.val = 0
  28. self.avg = 0
  29. self.sum = 0
  30. self.count = 0
  31. def update(self, val, n=1):
  32. """ update """
  33. self.val = val
  34. self.sum += val * n
  35. self.count += n
  36. self.avg = self.sum / self.count
  37. @property
  38. def total(self):
  39. return '{self.name}_sum: {self.sum:{self.fmt}}{self.postfix}'.format(
  40. self=self)
  41. @property
  42. def total_minute(self):
  43. return '{self.name} {s:{self.fmt}}{self.postfix} min'.format(
  44. s=self.sum / 60, self=self)
  45. @property
  46. def mean(self):
  47. return '{self.name}: {self.avg:{self.fmt}}{self.postfix}'.format(
  48. self=self) if self.need_avg else ''
  49. @property
  50. def value(self):
  51. return '{self.name}: {self.val:{self.fmt}}{self.postfix}'.format(
  52. self=self)