Created
November 29, 2018 12:00
-
-
Save amirmasoudabdol/26cae90b2cdf09be1b1c7cc505238858 to your computer and use it in GitHub Desktop.
This file contains 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
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