profiler.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from time import perf_counter as timer
  2. from collections import OrderedDict
  3. import numpy as np
  4. class Profiler:
  5. def __init__(self, summarize_every=5, disabled=False):
  6. self.last_tick = timer()
  7. self.logs = OrderedDict()
  8. self.summarize_every = summarize_every
  9. self.disabled = disabled
  10. def tick(self, name):
  11. if self.disabled:
  12. return
  13. # Log the time needed to execute that function
  14. if not name in self.logs:
  15. self.logs[name] = []
  16. if len(self.logs[name]) >= self.summarize_every:
  17. self.summarize()
  18. self.purge_logs()
  19. self.logs[name].append(timer() - self.last_tick)
  20. self.reset_timer()
  21. def purge_logs(self):
  22. for name in self.logs:
  23. self.logs[name].clear()
  24. def reset_timer(self):
  25. self.last_tick = timer()
  26. def summarize(self):
  27. n = max(map(len, self.logs.values()))
  28. assert n == self.summarize_every
  29. print("\nAverage execution time over %d steps:" % n)
  30. name_msgs = ["%s (%d/%d):" % (name, len(deltas), n) for name, deltas in self.logs.items()]
  31. pad = max(map(len, name_msgs))
  32. for name_msg, deltas in zip(name_msgs, self.logs.values()):
  33. print(" %s mean: %4.0fms std: %4.0fms" %
  34. (name_msg.ljust(pad), np.mean(deltas) * 1000, np.std(deltas) * 1000))
  35. print("", flush=True)