# -*- coding: utf-8 -*- """ @file timer.py @brief A class that will time and log by itself when it leaves scope as well as timer decorators. @par History - Brian Helgans, Dec 02 2019, updated to add log name as input """ import datetime from . import log as Log class Timer: ''' Timer for profiling and is used in the timethis decorator ''' def __init__(self, functionRunning, log = True): self.name = functionRunning self.start = Log.funcStart(self.name) if log else datetime.datetime.today() #gets the time logged at start. self.tDelta = datetime.timedelta() #< the time delta starts at 0 def stop(self, log = True): T1 = datetime.datetime.today() self.tDelta = T1 - self.start - self.tDelta formatted = self._totalSeconds(self.tDelta) if log: Log.info(self.name, "Ran for: " + formatted) return formatted def pause(self, log = True): """ pauses the timer """ T1 = datetime.datetime.today() self.tDelta = T1 - self.start - self.tDelta self.start = None if log: Log.info(self.name, "paused the timer") def unpause(self, log = True): """ pauses the timer """ self.start = datetime.datetime.today() if log: Log.info(self.name, "unpaused the timer") def _totalSeconds(self,tDelta): """ returns the time elapsed from start to the time parameter. """ return "{0:.2f}".format(tDelta.total_seconds()) + " seconds" def display(self, log = True): """ returns elapsed time but does not stop. """ T1 = log.funcFinish(self.name) tDelta = T1 - self.start - self.tDelta formatted = self._totalSeconds(self,tDelta) if log: Log.info(self.name, "routine has been running for: " + formatted) return formatted def timethis(func): """ decorate any function with this and the function will be timed :param func: :type func: """ def wrap(*args, **kwargs): #failed hack attempt at getting testname for logger (SCRIPT,TASK,function) #if inspect.isclass(args[0]): # if 'testname' in func.globals(): # timer = Timer(func.__qualname__,test=func.testname) # else: # timer = Timer(func.__qualname__,func.__file__) timer = Timer(func.__qualname__) func(*args, **kwargs) timer.stop() return return wrap