misc.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # Copyright (c) 2022 NVIDIA Corporation. All rights reserved.
  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:
  16. """
  17. A container to keep running sum, mean and last 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.val = 0
  25. self.avg = 0
  26. self.sum = 0
  27. self.count = 0
  28. def reset(self):
  29. self.val = 0
  30. self.avg = 0
  31. self.sum = 0
  32. self.count = 0
  33. def update(self, val, n=1):
  34. self.val = val
  35. self.sum += val * n
  36. self.count += n
  37. self.avg = self.sum / self.count
  38. @property
  39. def total(self):
  40. return '{self.sum:{self.fmt}}{self.postfix}'.format(self=self)