timer.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. # -*- coding: UTF-8 -*-
  2. import time, functools
  3. from collections import defaultdict
  4. import logging
  5. logger = logging.getLogger(__name__)
  6. class TotalTimer(object):
  7. def __init__(self):
  8. self.times = defaultdict(float)
  9. def add(self, name, t):
  10. self.times[name] += t
  11. def reset(self):
  12. self.times = defaultdict(float)
  13. def __del__(self):
  14. for k, v in self.times.items():
  15. logger.info("{} took {} seconds in total.".format(k, v))
  16. _total_timer = TotalTimer()
  17. class timing(object):
  18. def __init__(self, total=False):
  19. self.total = total
  20. def __call__(self, func):
  21. @functools.wraps(func)
  22. def wrapper(*args, **kwargs):
  23. start_time = time.time()
  24. ret = func(*args, **kwargs)
  25. duration = time.time() - start_time
  26. if hasattr(func, '__name__'):
  27. func_name = func.__name__
  28. else:
  29. func_name = 'function in module {}'.format(func.__module__)
  30. if self.total:
  31. _total_timer.add(func_name, duration)
  32. else:
  33. logger.info('Duration for `{}\': {}'.format(
  34. func_name, duration))
  35. return ret
  36. return wrapper