Skip to content

Instantly share code, notes, and snippets.

@amirmasoudabdol
Created November 29, 2018 12:00
Show Gist options
  • Save amirmasoudabdol/26cae90b2cdf09be1b1c7cc505238858 to your computer and use it in GitHub Desktop.
Save amirmasoudabdol/26cae90b2cdf09be1b1c7cc505238858 to your computer and use it in GitHub Desktop.
import time
from functools import wraps
def profiling_decorator(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
start_time = time.time()
res = f(*args, **kwargs)
end_time = time.time()
elapsed_time = end_time - start_time
print("[Time elapsed {}".format(elapsed_time))
return res
return wrapped_f
def profile_all_class_methods(Cls):
class ProfiledClass(object):
"""docstring for ProfiledClass"""
def __init__(self, *args, **kwargs):
self.inst = Cls(*args, **kwargs)
def __getattribute__(self, s):
try:
x = super(ProfiledClass, self).__getattribute__(s)
except AttributeError:
pass
else:
x = self.inst.__getattribute__(s)
if type(x) == type(self.__init__):
return profiling_decorator(x)
else:
return x
return ProfiledClass
@profile_all_class_methods
class DoMathStuff(object):
"""docstring for DoMathStuff"""
def __init__(self, n):
self.n = n
def fib(self):
fPrev, f = 1, 1
for num in xrange(2, self.n):
fPrev, f = f, f + fPrev
return f
@profiling_decorator
def fact(self):
fct = 1
for num in xrange(1, self.n):
fct *= num
return fct
if __name__ == '__main__':
m = DoMathStuff(10)
print("Fib = {}, Fact = {}".format(m.fib(), m.fact()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment