import time class TimerError(Exception): """ Manage timer errors """ class Timer: def __init__( self, text_out = '{}: Elapsed time: {:0.4f} seconds', text_in = 'Start {}', text_tag = 'Time elapsed for {}: {:0.4f} seconds', text_total = 'Total recorded time: {:0.4f} seconds', logger=print, ): self._start_time = None self.name = None self.text_in = text_in self.text_out = text_out self.text_tag = text_tag self.text_total = text_total self.logger = logger self.timers = {} def start(self, name='General'): """Start a new timer""" self.name = name # if timer does not exists, initiate it if not name in self.timers: self.timers[self.name] = 0 if self._start_time is not None: raise TimerError('Timer is running. Use .stop() to stop it') self.logger(self.text_in.format(self.name)) self._start_time = time.perf_counter() def stop(self): """Stop the timer, and report the elapsed time""" if self._start_time is None: raise TimerError('Timer is not running. Use .start() to start it') elapsed_time = time.perf_counter() - self._start_time self._start_time = None if self.logger: self.logger(self.text_out.format(self.name, elapsed_time)) if self.name: self.timers[self.name] += elapsed_time def get_time_by_tag(self, tag): if tag in self.timers: self.logger(self.text_tag.format(tag,self.timers[tag])) def get_total_time(self): total = 0 for v in self.timers.values(): total += v self.logger(self.text_total.format(total))