Skip to content

Instantly share code, notes, and snippets.

@ariel-co
Last active March 30, 2024 23:05
Show Gist options
  • Select an option

  • Save ariel-co/a45affb0097dadec78a8d792bf61c929 to your computer and use it in GitHub Desktop.

Select an option

Save ariel-co/a45affb0097dadec78a8d792bf61c929 to your computer and use it in GitHub Desktop.
context manager class for timing a code block
class Timer():
def __init__(self):
self.timer = time.perf_counter
def __enter__(self):
self.start = self.timer()
return self
def __exit__(self, *args):
self.elapsed = self.timer() - self.start
if __name__ == "__main__":
from time import sleep
with Timer() as t:
time.sleep(3)
print(f"Took {t.elapsed} seconds")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment