Many times we need to check the running time of a function, so that we can see which functions are taking a lot of time and improve them.
In this post I'm writing about a simple but elegant way to do this using Python Decorators.
Decorators are a design pattern in python that lets us modify the functionality of an object without changing its structure. Here I'll use this to modify a function to also print the time taken by it.
Lets see how I'm using this to track function run time:
Suppose we have a basic function which reads a csv and returns the pd.DataFrame. Now depending on the size of the csv, it can take some time to run.
Here we can define the function
calc_runtime which will act as a decorator for calculating runtime. This function will take a function
f as input and will return an updated version of the same function.
As the decorator is ready, we can simply call this over any function to print its runtime. Here we are calling over our target function like this :
load_csv gets passed on as an argument to the
calc_runtime, there we handle its arguments by using
kwargs easily. Finally we return the value to the calling space.
By using this kind of decorators, its straightforward to change the return value of a function, or print some additional layers over a function.