Skip to content

Instantly share code, notes, and snippets.

@osantana
Last active December 28, 2022 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save osantana/a794d262f9dd730b2eb69ffed6f81dc6 to your computer and use it in GitHub Desktop.
Save osantana/a794d262f9dd730b2eb69ffed6f81dc6 to your computer and use it in GitHub Desktop.
A simple timer implementation that supports clock injection
import time
from datetime import datetime
class Clock:
def now(self):
return datetime.now()
class Timer:
# or a simpler alternative...
def __init__(self, clock=None): # def __init__(self, now=datetime.now):
if clock is None: # self._now = now
clock = Clock()
self.clock = clock
self._start = None
self._stop = None
self._elapsed_time = None
def start(self):
self._start = self.clock.now() # self._start = self._now()
def stop(self):
self._stop = self.clock.now() # self._stop = self._now()
@property
def elapsed_time(self):
if not self._start:
raise ValueError("Timer not started")
if self._stop:
now = self._stop
else:
now = self.clock.now() # now = self._now()
self._elapsed_time = now - self._start
return self._elapsed_time
t = Timer()
t.start()
time.sleep(2)
t.stop()
print(t.elapsed_time) # prints ~0:00:02
class FakeClock:
def now(self):
return datetime(year=2022, month=12, day=28, hour=0, minute=0)
t = Timer(FakeClock())
t.start()
time.sleep(2)
t.stop()
print(t.elapsed_time) # prints 0:00:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment