Source code for luna_api.crutches_on_wheels.cow.utils.timer

"""Timers

Timer decorators

"""
import time
from functools import wraps
from typing import Callable

from vlutils.helpers import isCoroutineFunction

from ..utils.log import Logger


[docs]def printLogger(self: object, func: callable, duration: float) -> None: """ Print timing to log Args: self: class instance with logger func: measured function duration: calling duration of function in secs """ if hasattr(self, "logger"): self.logger.debug(f"{func.__qualname__} time: {round(duration, 5)}") else: Logger().debug(f"{func.__qualname__} time: {round(duration, 5)}")
[docs]def timer(func: callable) -> Callable: """ Decorator for function work time estimation. Args: func: decorating function Returns: decorated function. """ if isCoroutineFunction(func): @wraps(func) async def wrap(*func_args, **func_kwargs): start = time.perf_counter() res = await func(*func_args, **func_kwargs) end = time.perf_counter() printLogger(func_args and func_args[0], func, end - start) return res else: @wraps(func) def wrap(*func_args, **func_kwargs): start = time.perf_counter() res = func(*func_args, **func_kwargs) end = time.perf_counter() printLogger(func_args and func_args[0], func, end - start) return res return wrap