Python Decorator to Measure Elapsed Time


Measuring elpased time in python is very useful for peformance analysis. This program measures elpased time of python code using decorators.

In this program we design timer decorator and this decorator is used to decorate any function whose execution time need to measure.

Python Source Code: Timer Decorator


# Timer decorator

def timer(fn):
    from time import perf_counter
    
    def inner(*args, **kwargs):
        start_time = perf_counter()
        to_execute = fn(*args, **kwargs)
        end_time = perf_counter()
        execution_time = end_time - start_time
        print('{0} took {1:.8f}s to execute'.format(fn.__name__, execution_time))
        return to_execute
    
    return inner

@timer
def function_1():
    for i in range(100000):
        pass

@timer
def function_2():
    for i in range(10000000):
        pass

@timer
def function_3():
    for i in range(10000):
        pass

@timer
def function_4():
    for i in range(100000000):
        pass

function_1()
function_2()
function_3()
function_4()

Output

Output of the above program is:

function_1 took 0.00620240s to execute
function_2 took 0.79993060s to execute
function_3 took 0.00093230s to execute
function_4 took 8.81120080s to execute