Last active
March 30, 2024 23:05
-
-
Save ariel-co/a45affb0097dadec78a8d792bf61c929 to your computer and use it in GitHub Desktop.
context manager class for timing a code block
This file contains hidden or 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
| 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