From 3e151f3afb9efd6623a8d847f1d5ed83373930ab Mon Sep 17 00:00:00 2001 From: Geir Arne Hjelle Date: Fri, 2 Aug 2019 00:21:16 +0200 Subject: [PATCH 1/2] Split code into separate file --- codetiming/__init__.py | 66 ++---------------------------------------- codetiming/_timer.py | 64 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 63 deletions(-) create mode 100644 codetiming/_timer.py diff --git a/codetiming/__init__.py b/codetiming/__init__.py index c3b54e0..736871a 100644 --- a/codetiming/__init__.py +++ b/codetiming/__init__.py @@ -4,85 +4,25 @@ 1. As a **class**: - ```python t = Timer(name="class") t.start() # Do something t.stop() - ``` 2. As a **context manager**: - ```python with Timer(name="context manager"): # Do something - ``` 3. As a **decorator**: - ```python @Timer(name="decorator") def stuff(): # Do something - ``` """ -from contextlib import ContextDecorator -from dataclasses import dataclass, field -import time -from typing import Any, Callable, ClassVar, Dict, Optional +# Import Timer for cleaner namespace +from codetiming._timer import Timer, TimerError # noqa +# Versioning is handled by bump2version __version__ = "0.1.1" - - -class TimerError(Exception): - """A custom exception used to report errors in use of Timer class""" - - -@dataclass -class Timer(ContextDecorator): - """Time your code using a class, context manager, or decorator""" - - timers: ClassVar[Dict[str, float]] = dict() - name: Optional[str] = None - text: str = "Elapsed time: {:0.4f} seconds" - logger: Optional[Callable[[str], None]] = print - _start_time: Optional[float] = field(default=None, init=False, repr=False) - - def __post_init__(self) -> None: - """Initialization: add timer to dict of timers""" - if self.name: - self.timers.setdefault(self.name, 0) - - def start(self) -> None: - """Start a new timer""" - if self._start_time is not None: - raise TimerError(f"Timer is running. Use .stop() to stop it") - - self._start_time = time.perf_counter() - - def stop(self) -> float: - """Stop the timer, and report the elapsed time""" - if self._start_time is None: - raise TimerError(f"Timer is not running. Use .start() to start it") - - # Calculate elapsed time - elapsed_time = time.perf_counter() - self._start_time - self._start_time = None - - # Report elapsed time - if self.logger: - self.logger(self.text.format(elapsed_time)) - if self.name: - self.timers[self.name] += elapsed_time - - return elapsed_time - - def __enter__(self) -> "Timer": - """Start a new timer as a context manager""" - self.start() - return self - - def __exit__(self, *exc_info: Any) -> None: - """Stop the context manager timer""" - self.stop() diff --git a/codetiming/_timer.py b/codetiming/_timer.py new file mode 100644 index 0000000..da36aa9 --- /dev/null +++ b/codetiming/_timer.py @@ -0,0 +1,64 @@ +"""Definition of Timer + +See help(codetiming) for quick instructions, and +https://pypi.org/project/codetiming/ for more details +""" + +# Standard library imports +from contextlib import ContextDecorator +from dataclasses import dataclass, field +import time +from typing import Any, Callable, ClassVar, Dict, Optional + + +class TimerError(Exception): + """A custom exception used to report errors in use of Timer class""" + + +@dataclass +class Timer(ContextDecorator): + """Time your code using a class, context manager, or decorator""" + + timers: ClassVar[Dict[str, float]] = dict() + name: Optional[str] = None + text: str = "Elapsed time: {:0.4f} seconds" + logger: Optional[Callable[[str], None]] = print + _start_time: Optional[float] = field(default=None, init=False, repr=False) + + def __post_init__(self) -> None: + """Initialization: add timer to dict of timers""" + if self.name: + self.timers.setdefault(self.name, 0) + + def start(self) -> None: + """Start a new timer""" + if self._start_time is not None: + raise TimerError(f"Timer is running. Use .stop() to stop it") + + self._start_time = time.perf_counter() + + def stop(self) -> float: + """Stop the timer, and report the elapsed time""" + if self._start_time is None: + raise TimerError(f"Timer is not running. Use .start() to start it") + + # Calculate elapsed time + elapsed_time = time.perf_counter() - self._start_time + self._start_time = None + + # Report elapsed time + if self.logger: + self.logger(self.text.format(elapsed_time)) + if self.name: + self.timers[self.name] += elapsed_time + + return elapsed_time + + def __enter__(self) -> "Timer": + """Start a new timer as a context manager""" + self.start() + return self + + def __exit__(self, *exc_info: Any) -> None: + """Stop the context manager timer""" + self.stop() From 45208034c3ceb78ce0bada7709a9ce2c10d41f2e Mon Sep 17 00:00:00 2001 From: Geir Arne Hjelle Date: Fri, 2 Aug 2019 00:29:19 +0200 Subject: [PATCH 2/2] lint --- codetiming/_timer.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codetiming/_timer.py b/codetiming/_timer.py index da36aa9..e0b8f15 100644 --- a/codetiming/_timer.py +++ b/codetiming/_timer.py @@ -1,7 +1,7 @@ """Definition of Timer See help(codetiming) for quick instructions, and -https://pypi.org/project/codetiming/ for more details +https://pypi.org/project/codetiming/ for more details. """ # Standard library imports