Skip to content

Instantly share code, notes, and snippets.

@ducher
Last active August 29, 2015 14:04
Show Gist options
  • Save ducher/5fcf131812fe191ea2f8 to your computer and use it in GitHub Desktop.
Save ducher/5fcf131812fe191ea2f8 to your computer and use it in GitHub Desktop.
Class decorator to time between two methods, also working with self
import time
def TwoMethodsTimer(func1, func2): # On @ decorator
def ClassBuilder(aClass):
class Wrapper:
def __init__(self, *args, **kargs): # On instance creation
# stores the begining timestamp when timing
self.startTime = 0
# to start all the latencies, for statistics purpose
self.latencies = []
self.wrapped = aClass(*args, **kargs) # Use enclosing scope name"é
self.oldFunc1 = self.wrapped.__getattribute__(func1)
self.oldFunc2 = self.wrapped.__getattribute__(func2)
self.wrapped.__setattr__(func1, self.newFunc1)
self.wrapped.__setattr__(func2, self.newFunc2)
def startTimer(self):
self.startTime = time.time()
def stopTimer(self):
if self.startTime != 0:
totalTime = time.time() - self.startTime
self.latencies.append(totalTime)
print("Took "+str(totalTime)+" seconds for "+ str(self.wrapped.getID()) + " Average: "+str(sum(self.latencies)/float(len(self.latencies))))
self.startTime = 0
def callOrig(self):
getattr(self.wrapped, func2+'_old')()
def newFunc1(self, *args, **kargs):
self.startTimer()
return self.oldFunc1( *args, **kargs)
def newFunc2(self, *args, **kargs):
self.stopTimer()
return self.oldFunc2( *args, **kargs)
def __getattr__(self, attrname):
# to keep the original methods working
return getattr(self.wrapped, attrname) # Delegate to wrapped obj
return Wrapper
return ClassBuilder
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment