Skip to content

Instantly share code, notes, and snippets.

@vlagorsse
Created June 14, 2024 14:54
Show Gist options
  • Save vlagorsse/e64c6d523b8cbbd9d57f5cdde2206c11 to your computer and use it in GitHub Desktop.
Save vlagorsse/e64c6d523b8cbbd9d57f5cdde2206c11 to your computer and use it in GitHub Desktop.
python timer in context manager
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