timer.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import time
  2. class TimerSubcategory:
  3. def __init__(self, timer, category):
  4. self.timer = timer
  5. self.category = category
  6. self.start = None
  7. self.original_base_category = timer.base_category
  8. def __enter__(self):
  9. self.start = time.time()
  10. self.timer.base_category = self.original_base_category + self.category + "/"
  11. def __exit__(self, exc_type, exc_val, exc_tb):
  12. elapsed_for_subcategroy = time.time() - self.start
  13. self.timer.base_category = self.original_base_category
  14. self.timer.add_time_to_record(self.original_base_category + self.category, elapsed_for_subcategroy)
  15. self.timer.record(self.category)
  16. class Timer:
  17. def __init__(self):
  18. self.start = time.time()
  19. self.records = {}
  20. self.total = 0
  21. self.base_category = ''
  22. def elapsed(self):
  23. end = time.time()
  24. res = end - self.start
  25. self.start = end
  26. return res
  27. def add_time_to_record(self, category, amount):
  28. if category not in self.records:
  29. self.records[category] = 0
  30. self.records[category] += amount
  31. def record(self, category, extra_time=0):
  32. e = self.elapsed()
  33. self.add_time_to_record(self.base_category + category, e + extra_time)
  34. self.total += e + extra_time
  35. def subcategory(self, name):
  36. self.elapsed()
  37. subcat = TimerSubcategory(self, name)
  38. return subcat
  39. def summary(self):
  40. res = f"{self.total:.1f}s"
  41. additions = [(category, time_taken) for category, time_taken in self.records.items() if time_taken >= 0.1 and '/' not in category]
  42. if not additions:
  43. return res
  44. res += " ("
  45. res += ", ".join([f"{category}: {time_taken:.1f}s" for category, time_taken in additions])
  46. res += ")"
  47. return res
  48. def dump(self):
  49. return {'total': self.total, 'records': self.records}
  50. def reset(self):
  51. self.__init__()
  52. startup_timer = Timer()
  53. startup_record = None