Write a python decorator function to find how much time user given function takes to execute


Topic: Write a python decorator function to find how much time user given function takes to execute

Solution

def timed(fn):
    from time import perf_counter
    from functools import wraps
    @wraps(fn) 
    def inner(*args, **kwargs):
        start = perf_counter()
        result = fn(*args, **kwargs)
        end = perf_counter()
        elapsed = end - start
        args_ = [str(a) for a in args]
        kwargs_ = ['{0}={1}'.format(k, v) for k, v in kwargs.items()]
        all_args = args_ + kwargs_
        args_str = ','.join(all_args) # now it is comma delimited
        print(f'{fn.__name__}({args_str}) took {elapsed} seconds')
        return result
    # inner = wraps(fn)(inner)
    return inner



List all Python Programs