Using a Decorator to Measure Execution Time of a Function in Python

For profiling your application

Anh T. Dang
Level Up Coding

--

Let's assume that our function is:

def my_func(a, b):
retval = a+b
return retval

Now, we want to measure the time taken by this function. Simply, we add some lines to achieve this.

import time

def my_func(a, b):
start_time = time.time();
retval = a+b
print("the function ends in ", time.time()-start_time, "secs")
return retval

Storing the current time in start_time variable and then I let the method execute and then subtract the start_time from the current time to get the actual method execution time.

Output:

my_func(1, 2)
the function ends in 7.152557373046875e-07 secs

But we can do better using decorations to wrap any function.

from functools import wraps
import time

def timer(func):
@wraps(func)
def wrapper(a, b):
start_time = time.time();
retval = func(a, b)
print("the function ends in ", time.time()-start_time, "secs")
return retval
return wrapper

Now we can use this timer decorator to decorate the my_func function.

@timer
def my_func(a, b):
retval = a+b
return retval

When calling this function, we get the following result.

my_func(1, 2) 
the function ends in 1.1920928955078125e-06 secs

What if the function takes more than two variables since we don’t know how many arguments we are going to need?

Simply, we use *args allows us to pass a variable number of non-keyword arguments to a Python function.

def timer(func):
@wraps(func)
def wrapper(*args):
start_time = time.time();
retval = func(*args)
print("the function ends in ", time.time()-start_time, "secs")
return retval
return wrapper

We can add @timer to each of our functions for which we want to measure.

@timer
def my_func(a, b, c):
retval = a+b+c
return retval

Output:

my_func(1,2, 3)
the function ends in 1.6689300537109375e-06 secs

Easy, right?

--

--

I write about things that I like and things that I don’t, mainly in the business, art and tech sphere. Sign up for my newsletter http://junryo.xyz