DEV Community

Cover image for Calculating Run Time of a function using Python Decorators
Shubham Saxena
Shubham Saxena

Posted on

Calculating Run Time of a function using Python Decorators

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.

But, What is a Decorator?

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:

1. Target Function:

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.

image

2. Decorator Function:

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.

image

3. Using the Decorator over target 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 :

image

Basically the load_csv gets passed on as an argument to the calc_runtime, there we handle its arguments by using args
and 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.

Top comments (0)