Skip to content

Instantly share code, notes, and snippets.

@tudormunteanu
Created July 16, 2021 15:23
Show Gist options
  • Save tudormunteanu/048551753a7e5b785c08bbbcdd2e8903 to your computer and use it in GitHub Desktop.
Save tudormunteanu/048551753a7e5b785c08bbbcdd2e8903 to your computer and use it in GitHub Desktop.
Simple class useful for timing Python code.
class Timer:
"""Measure time used.
# Setup timer
>>> timer = Timer()
# Access as a string
>>> timer.print()
Time elapsed is 0:00:03.
>>> timer.print()
Time elapsed is 0:00:04.
# Access as a float
>>> timer()
6.841332235
>>> timer()
7.970274425
"""
# Ref: https://stackoverflow.com/a/57931660/
def __init__(self, round_ndigits: int = 0):
self._round_ndigits = round_ndigits
self._start_time = timeit.default_timer()
def __call__(self) -> float:
return timeit.default_timer() - self._start_time
def __str__(self) -> str:
return str(datetime.timedelta(seconds=round(self(), self._round_ndigits)))
def print(self):
print(f'Time elapsed is {self}.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment