Skip to content

Instantly share code, notes, and snippets.

@satrialoka
Created April 2, 2025 14:19
Show Gist options
  • Select an option

  • Save satrialoka/2677d04f267738f59f70b732e77723fb to your computer and use it in GitHub Desktop.

Select an option

Save satrialoka/2677d04f267738f59f70b732e77723fb to your computer and use it in GitHub Desktop.
useful python stuff
# 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