打印运行时间
import time
class PrintRunCycle(object):
def __init__(self):
self._start_time = None
def __enter__(self):
self._start_time = time.time()
def __exit__(self, exc_type, exc_val, exc_tb):
end_time = time.time()
print(f"运行时间: {end_time - self._start_time}s")
if __name__ == '__main__':
with PrintRunCycle():
print("---")
固定运行周期
import time
class FixedCycle(object):
def __init__(self, cycle_time):
"""
运行消耗时间 + 休眠时间 >= cycle_time
①如果运行代码有异常,直接抛弃,不休眠
②如果 cycle_time < 运行代码时间,不会强制终止运行, 优先将代码执行完
:param cycle_time: 单位 s
"""
self._cycle_time = cycle_time
def __enter__(self):
self._start_time = time.time()
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type or exc_val or exc_tb:
return
end_time = time.time()
run_cycle = end_time - self._start_time
need_sleep_time = max(self._cycle_time - run_cycle, 0)
print(f"运行消耗{run_cycle}s, 需要休眠{need_sleep_time}s")
time.sleep(need_sleep_time)
if __name__ == '__main__':
with FixedCycle(10):
print("joshua")
时间转时间戳
def time_in_timestamp(time_str: str, time_format="%Y-%m-%d %H:%M:%S") -> int:
"""
时间转时间戳
:return: 时间戳 单位:毫秒
"""
return int(time.mktime(time.strptime(time_str, time_format)) * 1000)
时间戳转时间
def timestamp_in_time(timestamp: int, time_format="%Y-%m-%d %H:%M:%S") -> str:
"""
时间戳转时间
:return: 时间字符串
"""
return time.strftime(time_format, time.localtime(timestamp * 0.001))