Created
June 4, 2024 05:27
-
-
Save rutcreate/53238f70c3beeca326e919f1fc9f573e to your computer and use it in GitHub Desktop.
Measure the elapsed time of a block of code using Python
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 | |
class Watcher: | |
""" | |
Measure the elapsed time of a block of code | |
Usage: | |
1. with statement: | |
with Watcher("loading something"): | |
# code to be measured | |
2. context manager: | |
w = Watcher("expensive operation") | |
w.start() | |
# code to be measured | |
w.end() | |
3. static method: | |
w = Watcher.watch("doing something") | |
# code to be measured | |
w.end() | |
""" | |
def __init__(self, message="Elapsed time"): | |
self.start_time = None | |
self.end_time = None | |
self.elapsed_time = None | |
self.message = message | |
def start(self): | |
self.start_time = time.time() | |
def end(self): | |
if self.start_time is None: | |
raise RuntimeError("Timer has not been started.") | |
self.end_time = time.time() | |
self.elapsed_time = self.end_time - self.start_time | |
print(f"{self.message}: {self.elapsed_time:.4f} seconds") | |
def __enter__(self): | |
self.start() | |
return self | |
def __exit__(self, exc_type, exc_value, traceback): | |
self.end() | |
@classmethod | |
def watch(cls, message): | |
return cls(message) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment