Skip to content

Instantly share code, notes, and snippets.

@diogobaeder
Created August 8, 2024 20:02
Show Gist options
  • Save diogobaeder/dbb31e4b99ca9738267d0631cde5106d to your computer and use it in GitHub Desktop.
Save diogobaeder/dbb31e4b99ca9738267d0631cde5106d to your computer and use it in GitHub Desktop.
contextmanager as with block and as decorator
#!/usr/bin/env python3
import time
from contextlib import contextmanager
@contextmanager
def timing():
start = time.time()
yield
elapsed = time.time() - start
print("Took", elapsed, "seconds to run")
@timing()
def foo():
print("foo will sleep")
time.sleep(0.2)
def bar():
with timing():
print("bar will sleep")
time.sleep(0.3)
if __name__ == '__main__':
foo()
bar()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment