from typing import Callable
from typing import Any
import cProfile


def do_cprofile(func: Callable, sort: str = "tottime") -> Callable:
    """
    Print profile stats to screen. To be used as a decorator for the function
    or method you want to profile. For example:

    .. code-block:: python

        profiled_func = do_cprofile(original_func)
        profiled_func(args_to_original_func)

    """
    def profiled_func(*args, **kwargs) -> Any:
        profile = cProfile.Profile()
        try:
            profile.enable()
            result = func(*args, **kwargs)
            profile.disable()
            return result
        finally:
            profile.print_stats(sort=sort)
    return profiled_func