Created
November 5, 2025 14:02
-
-
Save epicserve/32bfaebf4d1439e201b359c7e3b1f203 to your computer and use it in GitHub Desktop.
Example of using the rich library for a timing context manager
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
| import time | |
| from contextlib import contextmanager | |
| from datetime import timedelta | |
| from rich.align import Align | |
| from rich.columns import Columns | |
| from rich.console import Console | |
| from rich.padding import Padding | |
| from rich.style import Style | |
| from rich.text import Text | |
| def run_task(status_spinner=None): | |
| for i in range(20): | |
| if status_spinner is not None: | |
| status_spinner.update(f"Task {i}") | |
| time.sleep(0.1) | |
| def human_elapsed(seconds: float | timedelta): | |
| if isinstance(seconds, timedelta): | |
| seconds = seconds.total_seconds() | |
| if seconds < 1: | |
| return f"{seconds:.3f}s" | |
| parts = [] | |
| for unit, div in [("h", 3600), ("m", 60), ("s", 1)]: | |
| val, seconds = divmod(seconds, div) | |
| if val: | |
| if unit == "s" and seconds < 1: | |
| parts.append(f"{val:.3f}s") | |
| else: | |
| parts.append(f"{int(val)}{unit}") | |
| return " ".join(parts) or "<1ms" | |
| @contextmanager | |
| def timeit( | |
| title: str, | |
| spinner_color: Style = "blue", | |
| title_style: Style = "green", | |
| time_style: Style = "bold white", | |
| hide_spinner: bool = False, | |
| right_align_time: bool = True, | |
| ): | |
| start = time.perf_counter() | |
| console = Console() | |
| title = Text(title, style=title_style) | |
| if hide_spinner is True: | |
| yield None | |
| else: | |
| with console.status(title, spinner_style=spinner_color) as status: | |
| yield status | |
| elapsed = time.perf_counter() - start | |
| human_elapsed_text = Text(human_elapsed(elapsed), style=time_style) | |
| if right_align_time is True: | |
| human_elapsed_text = Padding(Align(human_elapsed_text, align="right"), (0, 1, 0, 0)) | |
| console.print(Columns([title, human_elapsed_text], expand=True)) | |
| else: | |
| console.print(title, human_elapsed_text) | |
| def main(): | |
| with timeit("Running task"): | |
| run_task() | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment