计算类执行时间的装饰器:
def __recordTimeClass(aClass):
class newClass():
def __init__(self):
self.CS_T = datetime.datetime.now()
self.wrapped= aClass()
self.CE_T = datetime.datetime.now()
def __scrDownload(self,url, minionid):
S_T=datetime.datetime.now()
results=self.wrapped.__scrDownload(url, minionid)
E_T=datetime.datetime.now()
return results
def executeScripts(self, params):
S_T = datetime.datetime.now()
a,b,c = self.wrapped.executeScripts(params)
E_T = datetime.datetime.now()
return a,b,c#,S_T,E_T
return newClass
计算普通函数执行时间的装饰器:
def __recordTime(): ''' record the run time of a function ''' def resFunc(func): def _resFunc(*args,**kwargs): S_T =datetime.datetime.now() results=func(*args,**kwargs) E_T =datetime.datetime.now() return results#,S_T,E_T return _resFunc return resFunc
使用类装饰器:
@__recordTimeClass class __TryParams(): def __init__(self): self.failure_minions={} self.success_minions={} self.script_lists = [] self.download_script_lists = [] def executeScripts(self,params): ''' :param: params{"url":"","minionid":"","parameter":{}} :return: ''' global OPT_PATH a=b=c=1 return a,b,c
使用函数装饰器:
@__recordTime() def __readScript(file_path): ''' #!# exec_module.py get the destination path to save the script file ''' lists=[] try: with open(file_path, 'r') as f: lines=f.readlines() for i in range(0,len(lines)): if lines[i].startswith("#!# need"): lists.append(lines[i]) except IOError,e: log.debug(e) return None return lists
重要的在于灵活运用,比如
S_T,E_T这两个全局变量,用在类装饰器里,就可以算一个总共运行时间或记录某几个方法执行的时间总和,从而分析性能瓶颈在哪