Last active
September 25, 2019 17:00
-
-
Save tweakimp/418293fdc53d9363fe121a8dafd55c5d to your computer and use it in GitHub Desktop.
Time code blocks
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
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