freqtrade_origin/freqtrade/util/measure_time.py

46 lines
1.3 KiB
Python
Raw Normal View History

import logging
import time
from typing import Callable
from cachetools import TTLCache
logger = logging.getLogger(__name__)
class MeasureTime:
"""
Measure the time of a block of code and call a callback if the time limit is exceeded.
"""
2024-05-12 14:56:05 +00:00
2024-04-17 18:58:58 +00:00
def __init__(
2024-05-12 14:56:05 +00:00
self, callback: Callable[[float, float], None], time_limit: float, ttl: int = 3600 * 4
):
"""
:param callback: The callback to call if the time limit is exceeded.
This callback will be called once every "ttl" seconds,
with the parameters "duration" (in seconds) and
"time limit" - representing the passed in time limit.
:param time_limit: The time limit in seconds.
:param ttl: The time to live of the cache in seconds.
2024-04-17 18:58:58 +00:00
defaults to 4 hours.
"""
self._callback = callback
self._time_limit = time_limit
2024-04-17 18:58:58 +00:00
self.__cache: TTLCache = TTLCache(maxsize=1, ttl=ttl)
def __enter__(self):
self._start = time.time()
def __exit__(self, *args):
end = time.time()
2024-05-12 14:56:05 +00:00
if self.__cache.get("value"):
return
duration = end - self._start
if duration < self._time_limit:
return
self._callback(duration, self._time_limit)
2024-05-12 14:56:05 +00:00
self.__cache["value"] = True