Created
July 16, 2021 15:23
-
-
Save tudormunteanu/048551753a7e5b785c08bbbcdd2e8903 to your computer and use it in GitHub Desktop.
Simple class useful for timing Python code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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