Skip to content

Instantly share code, notes, and snippets.

@nebil
Last active February 11, 2020 11: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 nebil/6f38f003319c0b947cb2f29262af6913 to your computer and use it in GitHub Desktop.
Save nebil/6f38f003319c0b947cb2f29262af6913 to your computer and use it in GitHub Desktop.
⏱️ listwatch -- a classy stopwatch for Python 3.3+
"""
stopwatch1.py -- a classy stopwatch for Python 3.3+
Copyright (c) 2020, Nebil Kawas García
This source code is subject to the terms of the Mozilla Public License.
You can obtain a copy of the MPL at <https://www.mozilla.org/MPL/2.0/>.
"""
from datetime import datetime
class Stopwatch:
"""
A minimalist stopwatch with a single-list approach.
"""
def __init__(self):
self.reset()
def reset(self):
self._timestamps = []
@staticmethod
def now():
return datetime.now().timestamp()
def switch(self):
self._timestamps.append(self.now())
@property
def is_ticking(self):
return len(self._timestamps) % 2 == 1
@property
def elapsed_time(self):
pauses = sum(self._timestamps[1::2], self.is_ticking * self.now())
starts = sum(self._timestamps[0::2])
return pauses - starts
def __str__(self):
return "{:.2f} seconds".format(self.elapsed_time)
if __name__ == "__main__":
watch = Stopwatch()
print(watch)
print(watch.is_ticking)
"""
stopwatch2.py -- a classy stopwatch for Python 3.3+
Copyright (c) 2020, Nebil Kawas García
This source code is subject to the terms of the Mozilla Public License.
You can obtain a copy of the MPL at <https://www.mozilla.org/MPL/2.0/>.
"""
from datetime import datetime
class Stopwatch:
"""
A minimalist stopwatch with a double-list approach.
"""
def __init__(self):
self.reset()
def reset(self):
self._pauses = []
self._starts = []
@staticmethod
def now():
return datetime.now().timestamp()
def switch(self):
if self.is_ticking:
self._pauses.append(self.now())
else:
self._starts.append(self.now())
@property
def is_ticking(self):
return len(self._pauses) != len(self._starts)
@property
def elapsed_time(self):
pauses = sum(self._pauses, self.is_ticking * self.now())
starts = sum(self._starts)
return pauses - starts
def __str__(self):
return "{:.2f} seconds".format(self.elapsed_time)
if __name__ == "__main__":
watch = Stopwatch()
print(watch)
print(watch.is_ticking)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment