Last active
May 14, 2019 08:06
-
-
Save checkaayush/2d72f3d306ade7e3cc39406f03567408 to your computer and use it in GitHub Desktop.
Python decorator function to calculate time taken by function to run
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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