Created
April 2, 2025 14:19
-
-
Save satrialoka/2677d04f267738f59f70b732e77723fb to your computer and use it in GitHub Desktop.
useful python stuff
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
| # Timer ############################################################################# | |
| import time | |
| class Timer: | |
| """ | |
| A simple context manager for timing code execution. | |
| Usage: | |
| with Timer() as t: | |
| # your code here | |
| time.sleep(2) | |
| print(f"Duration: {t.get_duration()} seconds") | |
| Methods: | |
| get_duration() -> float | |
| Returns the duration in seconds between entering and exiting the context. | |
| """ | |
| def __enter__(self): | |
| self._start = time.time() | |
| return self | |
| def __exit__(self, exc_type, exc_value, traceback): | |
| self._end = time.time() | |
| self.duration = self._end - self._start | |
| def get_duration(self) -> float: | |
| return self.duration |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment