Python decorator to measure the execution time of methods

Fahim Sakri
Apr 21, 2017 · 2 min read

Being a python developer you will always in need for profiling the application. In my current project my goal was figure out the bottleneck in the code. For that i had track the execution time for each methods.

So in the beginning, i started by storing the current time in start_time variable and then i let the method execute and then subtract the start_time with current time to get the actual method execution time as mentioned below:

start_time = int(round(time.time() * 1000))
employees = Employee.get_all_employee_details()
time_diff = current_milli_time() — start_time debug_log_time_diff.update({'FETCH_TIME': time_diff})

There is no issue with the above line of code but you know, this will significantly keep on increasing when you have many method/function call. At one point, it will be difficult to figure out the actual code and what you will see is the repetition of this code.

To overcome this, created the @timeit decorator which allows you to measure the execution time of the method/function by just adding the @timeit decorator on the method.

@timeit decorator:

def timeit(method):
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
if 'log_time' in kw:
name = kw.get('log_name', method.__name__.upper())
kw['log_time'][name] = int((te - ts) * 1000)
print '%r %2.2f ms' % \
(method.__name__, (te - ts) * 1000)
return result
return timed

Adding decorator to the method

def get_all_employee_details(**kwargs):
print 'employee details'

The code will look like this after removing the redundant code.

logtime_data ={}
employees = Employee.get_all_employee_details(log_time=logtime_data)

Hurray!! All that messy code is gone and now it looks simple and clear.

log_time and log_name are optional. Make use of them accordingly when needed.

Other articles


Python Decorator for execution time

P.S. Thanks for reading this far! If you found value in this, I’d really appreciate it if you recommend this post (by clicking the ❤ button) so other people can see it!.


PythonHive on Medium should be some kind of living room for…

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store