Last active
August 1, 2021 10:50
-
-
Save Nivratti/3b8b839072cad08ae72778dbdc81edb5 to your computer and use it in GitHub Desktop.
Python timer class
This file contains hidden or 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
# timer.py | |
""" | |
Usage: | |
>>> from timer import Timer | |
>>> t = Timer() ## or for logger: t = Timer(logger=logger.info) | |
>>> t.start() | |
>>> t.stop() # A few seconds later | |
Elapsed time: 3.8191 seconds | |
""" | |
import time | |
class TimerError(Exception): | |
"""A custom exception used to report errors in use of Timer class""" | |
class Timer: | |
def __init__(self, text="Elapsed time: {:0.4f} seconds", logger=print): | |
""" | |
Init | |
Args: | |
text (str, optional): Text format. Defaults to "Elapsed time: {:0.4f} seconds". | |
logger (logger type, optional): Either print or logger.info function. Defaults to print. | |
""" | |
self._start_time = None | |
self.text = text | |
self.logger = logger | |
def start(self): | |
"""Start a new timer""" | |
if self._start_time is not None: | |
raise TimerError(f"Timer is running. Use .stop() to stop it") | |
self._start_time = time.perf_counter() | |
def stop(self): | |
"""Stop the timer, and report the elapsed time""" | |
if self._start_time is None: | |
raise TimerError(f"Timer is not running. Use .start() to start it") | |
elapsed_time = time.perf_counter() - self._start_time | |
self._start_time = None | |
if self.logger: | |
self.logger(self.text.format(elapsed_time)) | |
return elapsed_time | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment