Last active
November 7, 2022 21:14
-
-
Save gwerbin/11dd868874b8188c46a89d750d641b33 to your computer and use it in GitHub Desktop.
Basic start/stop timer context manager
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
# TODO: Thread & async safety | |
import sys | |
import time | |
from collections.abc import Callable | |
if sys.version_info >= (3, 11): | |
from typing import Self | |
else: | |
from typing_extensions import Self | |
class Timer: | |
time: Callable[[], float] | |
t0: float | None | |
t1: float | None | |
def __init__(self, time: Callable[[], float] = time.perf_counter) -> None: | |
self.time = time | |
self.t0 = None | |
self.t1 = None | |
def reset(self) -> None: | |
self.t0 = None | |
self.t1 = None | |
def start(self) -> None: | |
if self.t0 is not None: | |
raise RuntimeError("Timer is already running!") | |
self.t0 = self.time() | |
def mark(self) -> None: | |
if self.t0 is None: | |
raise RuntimeError("Timer was not started!") | |
self.t1 = self.time() | |
def elapsed(self) -> None: | |
if self.t0 is None: | |
raise RuntimeError("Timer was not started!") | |
if self.t1 is not None: | |
raise RuntimeError("Timer was not marked!") | |
return self.t1 - self.t0 | |
def __enter__(self) -> Self: | |
self.start() | |
def __exit__(self, *_: object) -> None: | |
self.mark() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment