timer.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # Copyright (c) 2020 PaddlePaddle Authors. 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. import time
  15. class TimeAverager(object):
  16. def __init__(self):
  17. self.reset()
  18. def reset(self):
  19. self._cnt = 0
  20. self._total_time = 0
  21. self._total_samples = 0
  22. def record(self, usetime, num_samples=None):
  23. self._cnt += 1
  24. self._total_time += usetime
  25. if num_samples:
  26. self._total_samples += num_samples
  27. def get_average(self):
  28. if self._cnt == 0:
  29. return 0
  30. return self._total_time / float(self._cnt)
  31. def get_ips_average(self):
  32. if not self._total_samples or self._cnt == 0:
  33. return 0
  34. return float(self._total_samples) / self._total_time
  35. def calculate_eta(remaining_step, speed):
  36. if remaining_step < 0:
  37. remaining_step = 0
  38. remaining_time = int(remaining_step * speed)
  39. result = "{:0>2}:{:0>2}:{:0>2}"
  40. arr = []
  41. for i in range(2, -1, -1):
  42. arr.append(int(remaining_time / 60**i))
  43. remaining_time %= 60**i
  44. return result.format(*arr)