Python

How to measure execution time of a Python Function ?

For every python developer, execution time of his code is a major concern. And he/she try several methods to reduce the execution time and optimise his/her code.

For this, there are various methods available to check where the code is taking time and where the optimisation is need to be done.

Profiling is one of the method, either cProfile or Line Profiler is helpful in this case.

There is one of the technique used by many of the programmers to see which function is taking time or just to see what is the execution time of any function.

Timeit is one of strategy to check how much time a process or function is taking.

For this we will create one decorator named as timeit and put it over the function of which we need to find out the execution time.

import time

def timeit(func):
    def check_time(*args, **kwargs):
        time_start = time.time()
        process = func(*args, **kwargs)
        time_end = time.time()
        print('%r %2.2f s' % (func.__name__, time_end-time_start))
        return process
    return check_time

Add this decorator to the method

@timeit
def add(num1, num2):
    print(num1 + num2)

Now run the code

add(2,3)
5
'add' 0.01 s

Here you will see the add takes 0.01 seconds to process it.

Thanks ! Happy Coding 🙂