time.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. # coding=utf-8
  2. # Powered by SoaringNova Technology Company
  3. import errno
  4. import os
  5. import signal
  6. import time
  7. from collections import defaultdict
  8. from functools import wraps
  9. timer_counts = defaultdict(int)
  10. class TimeoutError(Exception):
  11. pass
  12. def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
  13. def decorator(func):
  14. def _handle_timeout(signum, frame):
  15. raise TimeoutError(error_message)
  16. def wrapper(*args, **kwargs):
  17. signal.signal(signal.SIGALRM, _handle_timeout)
  18. signal.alarm(seconds)
  19. try:
  20. result = func(*args, **kwargs)
  21. finally:
  22. signal.alarm(0)
  23. return result
  24. return wraps(func)(wrapper)
  25. return decorator
  26. class TIMELIMIT:
  27. def __init__(self, limit_time=0):
  28. self.st = None
  29. self.et = None
  30. self.limit_time = limit_time
  31. def __enter__(self):
  32. self.st = time.time()
  33. def __exit__(self, exc_type, exc_val, exc_tb):
  34. self.et = time.time()
  35. dt = self.limit_time - (self.et - self.st) * 1000
  36. if dt > 0: time.sleep(float(dt) / 1000)
  37. class TIMER:
  38. total_time = {} # type: dict
  39. def __init__(self, tag='', enable_total=False, threshold_ms=0):
  40. self.st = None
  41. self.et = None
  42. self.tag = tag
  43. # self.tag = tag if not hasattr(g,'request_id') else '{} {}'.format(getattr(g,'request_id'),tag)
  44. self.thr = threshold_ms
  45. self.enable_total = enable_total
  46. if self.enable_total:
  47. if self.tag not in self.total_time.keys():
  48. self.total_time[self.tag] = []
  49. def __enter__(self):
  50. self.st = time.time()
  51. def __exit__(self, exc_type, exc_val, exc_tb):
  52. self.et = time.time()
  53. dt = (self.et - self.st) * 1000
  54. if self.enable_total:
  55. self.total_time[self.tag].append(dt)
  56. if dt > self.thr:
  57. print("{}: {}s".format(self.tag, round(dt / 1000, 4)))
  58. @staticmethod
  59. def output():
  60. for k, v in TIMER.total_time.items():
  61. print('{} : {}s, avg{}s'.format(k, round(sum(v) / 1000, 2), round(sum(v) / len(v) / 1000, 2)))
  62. def timeit(func):
  63. @wraps(func)
  64. def wrapper(*args, **kwargs):
  65. st = time.time()
  66. ret = func(*args, **kwargs)
  67. dt = time.time() - st
  68. endpoint = '{}.{}'.format(func.__module__, func.__name__)
  69. timer_counts[endpoint] += 1
  70. print('{}[{}] finished, exec {}s'.format(endpoint, '%05d' % timer_counts[endpoint], round(dt, 4)))
  71. return ret
  72. return wrapper # 返回
  73. def t2date(t):
  74. import datetime
  75. date = datetime.datetime.fromtimestamp(t)
  76. return '{}_{}_{}_{}:{}:{}'.format(date.year, date.month, date.day, date.hour, date.minute, date.second)
  77. def day_begin(t):
  78. dsecs = 24 * 3600
  79. return (int(t) + 8 * 3600) // dsecs * dsecs - 8 * 3600
  80. def hour_begin(t):
  81. hsecs = 3600
  82. return (int(t) + 8 * 3600) // hsecs * hsecs - 8 * 3600