# -*- coding: utf-8 -*-## This file is subject to the terms and conditions defined in# file 'LICENSE.txt', which is part of this source code package.#fromtypingimportDict,List,Unionimporttimeimportfunctools
[docs]classTimer():"""Utility class to measure time spend in the code """almanac={}# type: Dict[str, List[Union[float, int]] ]def__init__(self,name=None):self.name=nameself.startTime=0.self.stopTime=0.ifnotnameinTimer.almanac:# cumulative time and number of time calledTimer.almanac[name]=[0.,0]def__enter__(self):"""Context implementation """self.Start()def__exit__(self,type,value,traceback):"""Context implementation """self.Stop()def__str__(self)->str:"""Return the time for the current instance if already used if no return PrintTimes Returns ------- str a string with the times store internally """ifself.startTime==0andself.stopTime==0:returnself.PrintTimes()res=""val=self.almanac[self.name]res+="\n"+str(self.name)+": "+str(time.time()-self.startTimeifself.stopTime==0elseself.stopTime-self.startTime)+" ("+str(val[1])+") : "+'{:6.3e}'.format(val[0])+" s (mean {:6.3e} s/call)".format(val[0]/val[1])returnres
[docs]@classmethoddefPrintTimes(cls)->str:"""Return the times recorded by Timer in string format Returns ------- str a string with all the data """res=""forname,valincls.almanac.items():ifnameisNone:continueres+="\n"+str(name)+": ("+str(val[1])+") : "+'{:6.3e}'.format(val[0])+" s (mean {:6.3e} s/call)".format(val[0]/val[1])returnres
[docs]defStart(self):"""Start the timer for the current instance Returns ------- Timer self """self.startTime=time.time()returnself
[docs]defStop(self):"""Stop the timer for the current instance Returns ------- Timer self """self.stopTime=time.time()data=Timer.almanac[self.name]data[0]+=self.GetDiffTime()data[1]+=1
[docs]defReset(self):"""Reset the internal storage (all measured times) """Timer.almanac={}
[docs]defGetDiffTime(self)->float:"""Return the elapsed time measured by this instance Returns ------- float the elapsed time measured by this instance """returnself.stopTime-self.startTime
def__call__(self,func):"""Support using timer as decorator"""@functools.wraps(func)defwrapper_timer(*args,**kwargs):withself:returnfunc(*args,**kwargs)returnwrapper_timer