timer.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import os
  2. try:
  3. TIMINGS = bool(os.environ['SCCDTIMINGS']=="1")
  4. except KeyError:
  5. TIMINGS = False
  6. if TIMINGS:
  7. from typing import Dict, Tuple
  8. import time
  9. import atexit
  10. import collections
  11. timings: Dict[str, Tuple[float, int]] = {}
  12. class Context:
  13. __slots__ = ["what", "started"]
  14. def __init__(self, what):
  15. self.what = what
  16. def __enter__(self):
  17. self.started = time.perf_counter()
  18. def __exit__(self, type, value, traceback):
  19. duration = time.perf_counter() - self.started
  20. old_val, old_count = timings.setdefault(self.what, (0, 0))
  21. timings[self.what] = (old_val + duration, old_count + 1)
  22. def _print_stats():
  23. print("\ntimings:")
  24. for key, (val,count) in sorted(timings.items()):
  25. print(" %s: %.2f ms / %d = %.3f ms" % (key,val*1000,count,val*1000/count))
  26. atexit.register(_print_stats)
  27. else:
  28. class Context:
  29. __slots__ = []
  30. def __init__(self, what):
  31. pass
  32. def __enter__(self):
  33. pass
  34. def __exit__(self, type, value, traceback):
  35. pass