A community web log for monkey niches.

utils.py 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import collections
  2. import copy
  3. import time
  4. import threading
  5. class Counters(object):
  6. def __init__(self):
  7. self.counters = collections.defaultdict(int)
  8. self.lock = threading.Lock()
  9. self.counters['id'] = id(self)
  10. def bump(self, name, arg=None):
  11. if not isinstance(name, str):
  12. name = name.__class__.__name__
  13. if '.' in name:
  14. name = name[name.rindex('.')+1:]
  15. if arg:
  16. name = '%s/%s' % (name, arg)
  17. with self.lock:
  18. self.counters[name] += 1
  19. def get_snapshot(self):
  20. with self.lock:
  21. return copy.copy(self.counters)
  22. def now():
  23. """Return the current time in the right epoch."""
  24. return time.time()
  25. def ago(timestamp):
  26. """Turn a timestamp into a string saying how long ago the
  27. timestamp was.
  28. """
  29. elapsed = now() - timestamp
  30. elapsed = max(1, elapsed)
  31. seconds = elapsed
  32. minutes = seconds / 60
  33. hours = minutes / 60
  34. days = hours / 24
  35. weeks = days / 7
  36. months = days / 30.5
  37. years = days / 365
  38. if seconds < 60:
  39. v, suffix = seconds, 'second'
  40. elif minutes <= 60:
  41. v, suffix = minutes, 'minute'
  42. elif hours <= 48:
  43. v, suffix = hours, 'hour'
  44. elif days <= 14:
  45. v, suffix = days, 'day'
  46. elif weeks < 12:
  47. v, suffix = weeks, 'week'
  48. elif months < 24:
  49. v, suffix = months, 'month'
  50. else:
  51. v, suffix = years, 'year'
  52. v = int(v)
  53. if v != 1:
  54. return '%s %ss' % (v, suffix)
  55. else:
  56. return '%s %s' % (v, suffix)