Skip to content

Instantly share code, notes, and snippets.

@checkaayush
Last active May 14, 2019 08:06
Show Gist options
  • Save checkaayush/2d72f3d306ade7e3cc39406f03567408 to your computer and use it in GitHub Desktop.
Save checkaayush/2d72f3d306ade7e3cc39406f03567408 to your computer and use it in GitHub Desktop.
Python decorator function to calculate time taken by function to run
from functools import wraps
import time
def timeit(func):
"""Decorator to calculate time taken by a function to run"""
@wraps(func)
def timed(*args, **kw):
start = time.time()
result = func(*args, **kw)
end = time.time()
format_str = 'function "{f}" took {took:.3f} seconds'
message = format_str.format(f=func.__name__, took=end - start)
# Use logger if provided
if kw.get('logger') is not None:
kw.get('logger').info(message)
else:
print(message)
return result
return timed
@timeit
def sayhi(name):
print("Hi {}!".format(name))
time.sleep(1)
sayhi("Aayush")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment