Created
June 14, 2024 14:54
-
-
Save vlagorsse/e64c6d523b8cbbd9d57f5cdde2206c11 to your computer and use it in GitHub Desktop.
python timer in context manager
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
from timeit import default_timer | |
class Timer(object): | |
def __init__(self, name: str, verbose: bool = True): | |
self.name = name | |
self.verbose = verbose | |
self.timer = default_timer | |
def __enter__(self): | |
self.start = self.timer() | |
return self | |
def __exit__(self, *args): | |
end = self.timer() | |
elapsed = (end - self.start) * 1000 # ms | |
if self.verbose: | |
print(f"{self.name} elapsed time: {elapsed} ms") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment