Skip to content

Instantly share code, notes, and snippets.

@seanpianka
Created June 17, 2018 01:18
Show Gist options
  • Save seanpianka/21e8a68a7c05f570a05470f2798c7d03 to your computer and use it in GitHub Desktop.
Save seanpianka/21e8a68a7c05f570a05470f2798c7d03 to your computer and use it in GitHub Desktop.
Stopwatch
import copy
import time
import sys
class StopyException(Exception):
pass
class IncompatibleStatesError(StopyException):
pass
class Stopwatch:
_default_time = {
"created": time.time(),
"started": 0,
"stopped": 0,
"difference": 0,
}
def __init__(self):
self.running = False
self.stopped = True
self.paused = False
self._time = {}
self._records = []
self._reset()
def _validate_state(states):
def validate_state(func):
def action(self):
valid_state = any(
[
[
getattr(self, attr) == group[attr]
for attr in group.keys()
]
for group in states
]
)
if not valid_state: raise IncompatibleStatesError
func(self)
return action
return validate_state
def _reset(self):
self._time = copy.copy(Stopwatch._default_time)
def _save(self, record):
self._records.append(record)
@_validate_state([{'stopped': 1, 'paused': 0}, {'stopped': 0, 'paused': 1}])
def start(self):
self.set(running=True)
self._time["started"] = time.time()
@_validate_state([{'running': 1, 'paused': 0}, {'paused': 1, 'running': 0}])
def stop(self, save=True):
self.set(stopped=True)
self._time['stopped'] = time.time()
self._time['difference'] = self._time['stopped'] - self._time['started']
if save: self._save(self._time)
self._reset()
@_validate_state([{'running':1,'stopped':0,'paused':0}])
def pause(self):
self.set(paused=True)
@_validate_state([{'running':0,'stopped':0,'paused':1}])
def resume(self):
self.set(running=True)
def restart(self):
self.stop(save=False)
self.start()
def set(self, running=False, stopped=False, paused=False):
states = [running, stopped, paused]
if not any(states) or sum(states) != 1:
raise ValueError("Only one state must be set.")
self.running = running
self.stopped = stopped
self.paused = paused
def export(self):
return self._records
def __str__(self):
return str(self._records)
c = Stopwatch()
c.start()
time.sleep(10)
c.stop()
print(c.export())
print(time.time())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment