Python: Timing Decoratoro

There was a discussion on the slack about timing functions to get some perf data and I remebered I had this beauty laying around.

import functools
from timeit import default_timer as timer


def deco_timer(self, func):
    """
    DECORATOR: Use to get an automatic start/stop message around the function
    prints metadata of function.__class__.__qualname__ Started/Finished
    so we can track times

    @yourLib.deco_timer
    def some_func():
        pass
    Args:
        func (function): function to wrap

    Returns:
        function: wrapped function
    """

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        """Wrapper function for tracking time taken for a given function"""
        if hasattr(func, "__call__"):
            name = func.__module__
        else:
            name = func.__class__
        start_time = timer()
        start_metadata = f"{name}.{func.__qualname__}"

        print(start_metadata)

        # run wrapped func
        out_val = func(*args, **kwargs)

        # log the time taken just for the sake of it
        time_taken = "{:4f}".format(timer() - start_time)

        finish_metadata = f"{name}.{func.__qualname__} : Time Taken:{time_taken}"

        print(finish_metadata)

        return out_val

    return wrapper

I usually put this in a utils.py somewhere on PATH and it makes it easy to put around the code base if/when you want to check things as you can then just do

import utils

@utils.deco_timer
def foo():

Hope it helps :slight_smile:

1 Like