Skip to content

Instantly share code, notes, and snippets.

@tweakimp
Last active September 25, 2019 17:00
Show Gist options
  • Save tweakimp/418293fdc53d9363fe121a8dafd55c5d to your computer and use it in GitHub Desktop.
Save tweakimp/418293fdc53d9363fe121a8dafd55c5d to your computer and use it in GitHub Desktop.
Time code blocks
import time
from contextlib import contextmanager
@contextmanager
def time_this(label):
start = time.perf_counter_ns()
try:
yield
finally:
end = time.perf_counter_ns()
text = f"{ label}" if label else label
print(f"TIME{f'{text}': {(end-start)/1000000000} sec")
# Use like this
if __name__ == "__main__":
with time_this("square rooting"):
for n in range(10 ** 7):
x = n ** 0.5
# returns:
# TIME square rooting: 2.307249782 sec
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment