sxtime.py 3.4 KB

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