#!/bin/python import time import logging logger = logging.getLogger(__name__) class Clock(object): def __init__(self, stopped=False): self._base = time.time() logging.info('Clock created. ' + 'Stopped = ' + str(stopped) + ', Base = ' + str(self._base)) self.stopped = stopped def stop(self): if not self.stopped: self.stopped_raw_time = time.time() logging.info('Clock stopped at ' + str(self.time)) self.stopped = True else: logging.warning('Attempt to stop the clock at ' + str(self.time) + ' - Clock already stopped!') def start(self): if self.stopped: logging.info('Clock started at ' + str(self.time)) delta = time.time() - self.stopped_raw_time self._base += delta self.stopped = False else: logging.warning('Attempted clock start at ' + str(self.time) + ' - Clock already running!') @property def time(self): if self.stopped: return self.stopped_raw_time - self._base else: return time.time() - self._base if __name__ == '__main__': logging.basicConfig(level=logging.INFO) clock = Clock() print 'Base = ', clock._base print clock.time print 'started, wait 5' time.sleep(5) print clock.time, '\n' clock.stop() print 'stopped, wait 5' time.sleep(5) print clock.time, '\n' print 'Stopping, but already stopped' clock.stop() print 'waiting 3 sec' time.sleep(3) print 'after 3 sec - ', clock.time, '\n' clock.start() print 'Started, wait 5' time.sleep(5) print clock.time, '\n' print 'Starting, but already started' clock.start() print 'waiting 3 sec' time.sleep(3) print 'After 3 -', clock.time