Skip to content

Timer utils

timer_utils #

Functions:

Name Description
timed_context

Context manager to measure the execution time of a block of code and log it with a custom name.

timer

Decorator to measure the execution time of a function and log it with a custom name.

timed_context #

timed_context(
    name: str,
) -> imgtools.utils.timer_utils.TimerContext

Context manager to measure the execution time of a block of code and log it with a custom name.

Returns:

Type Description
TimerContext:

A context manager that measures the execution time of a block of code.

Example
with timed_context("My Block"):
    # do something

# Output: `My Block took 3.1244 seconds`
Source code in src/imgtools/utils/timer_utils.py
def timed_context(name: str) -> TimerContext:
    """
    Context manager to measure the execution time of a block of code and log it with a custom name.

    Parameters
    ----------
        name (str): The custom name to use in the log message.

    Returns
    -------
        TimerContext:
        A context manager that measures the execution time of a block of code.

    Example
    -------
        with timed_context("My Block"):
            # do something

        # Output: `My Block took 3.1244 seconds`
    """
    return TimerContext(name)

timer #

timer(
    name: str,
) -> typing.Callable[
    [typing.Callable[..., typing.Any]],
    typing.Callable[..., typing.Any],
]

Decorator to measure the execution time of a function and log it with a custom name.

Returns:

Type Description
Callable[[Callable[..., Any]], Callable[..., Any]]:

A decorator that wraps the function to measure its execution time.

Example
@timer("My Function")
def my_function():
    # do something

my_function()
# Output: `My Function took 3.1244 seconds`
Source code in src/imgtools/utils/timer_utils.py
def timer(name: str) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
    """
    Decorator to measure the execution time of a function and log it with a custom name.

    Parameters
    ----------
        name (str): The custom name to use in the log message.

    Returns
    -------
        Callable[[Callable[..., Any]], Callable[..., Any]]:
        A decorator that wraps the function to measure its execution time.

    Example
    -------
        @timer("My Function")
        def my_function():
            # do something

        my_function()
        # Output: `My Function took 3.1244 seconds`
    """

    def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
        @wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Any:  # noqa
            with TimerContext(name):
                result = func(*args, **kwargs)
            return result

        return wrapper

    return decorator