timer.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import os
  2. import atexit
  3. if "MUMLE_PROFILER" in os.environ:
  4. import time
  5. timings = {}
  6. class Timer:
  7. def __init__(self, text):
  8. self.text = text
  9. def __enter__(self):
  10. self.start_time = time.perf_counter_ns()
  11. def __exit__(self, exc_type, exc_value, traceback):
  12. self.end_time = time.perf_counter_ns()
  13. duration = self.end_time - self.start_time
  14. existing_timing, count = timings.get(self.text, (0, 0))
  15. timings[self.text] = (existing_timing + duration, count+1)
  16. def __print_timings():
  17. if len(timings)>0:
  18. print(f'Timings:')
  19. tuples = [(text,(duration,count)) for text, (duration, count) in timings.items()]
  20. tuples.sort(key=lambda tup: -tup[1][0])
  21. for text, (duration, count) in tuples:
  22. print(f' {text} {round(duration/1000000)} ms ({count} times, {round(duration/count/1000000)} ms avg.)')
  23. atexit.register(__print_timings)
  24. else:
  25. class Timer:
  26. def __init__(self, text):
  27. pass
  28. def __enter__(self):
  29. pass
  30. def __exit__(self, exc_type, exc_value, traceback):
  31. pass
  32. def counted(f):
  33. def wrapped(*args, **kwargs):
  34. wrapped.calls += 1
  35. return f(*args, **kwargs)
  36. wrapped.calls = 0
  37. def ccc():
  38. print(f'{f} was called {wrapped.calls} times')
  39. atexit.register(ccc)
  40. return wrapped