|
4 | 4 |
|
5 | 5 | 1. As a **class**: |
6 | 6 |
|
7 | | - ```python |
8 | 7 | t = Timer(name="class") |
9 | 8 | t.start() |
10 | 9 | # Do something |
11 | 10 | t.stop() |
12 | | - ``` |
13 | 11 |
|
14 | 12 | 2. As a **context manager**: |
15 | 13 |
|
16 | | - ```python |
17 | 14 | with Timer(name="context manager"): |
18 | 15 | # Do something |
19 | | - ``` |
20 | 16 |
|
21 | 17 | 3. As a **decorator**: |
22 | 18 |
|
23 | | - ```python |
24 | 19 | @Timer(name="decorator") |
25 | 20 | def stuff(): |
26 | 21 | # Do something |
27 | | - ``` |
28 | 22 | """ |
29 | 23 |
|
30 | | -from contextlib import ContextDecorator |
31 | | -from dataclasses import dataclass, field |
32 | | -import time |
33 | | -from typing import Any, Callable, ClassVar, Dict, Optional |
| 24 | +# Import Timer for cleaner namespace |
| 25 | +from codetiming._timer import Timer, TimerError # noqa |
34 | 26 |
|
| 27 | +# Versioning is handled by bump2version |
35 | 28 | __version__ = "0.1.1" |
36 | | - |
37 | | - |
38 | | -class TimerError(Exception): |
39 | | - """A custom exception used to report errors in use of Timer class""" |
40 | | - |
41 | | - |
42 | | -@dataclass |
43 | | -class Timer(ContextDecorator): |
44 | | - """Time your code using a class, context manager, or decorator""" |
45 | | - |
46 | | - timers: ClassVar[Dict[str, float]] = dict() |
47 | | - name: Optional[str] = None |
48 | | - text: str = "Elapsed time: {:0.4f} seconds" |
49 | | - logger: Optional[Callable[[str], None]] = print |
50 | | - _start_time: Optional[float] = field(default=None, init=False, repr=False) |
51 | | - |
52 | | - def __post_init__(self) -> None: |
53 | | - """Initialization: add timer to dict of timers""" |
54 | | - if self.name: |
55 | | - self.timers.setdefault(self.name, 0) |
56 | | - |
57 | | - def start(self) -> None: |
58 | | - """Start a new timer""" |
59 | | - if self._start_time is not None: |
60 | | - raise TimerError(f"Timer is running. Use .stop() to stop it") |
61 | | - |
62 | | - self._start_time = time.perf_counter() |
63 | | - |
64 | | - def stop(self) -> float: |
65 | | - """Stop the timer, and report the elapsed time""" |
66 | | - if self._start_time is None: |
67 | | - raise TimerError(f"Timer is not running. Use .start() to start it") |
68 | | - |
69 | | - # Calculate elapsed time |
70 | | - elapsed_time = time.perf_counter() - self._start_time |
71 | | - self._start_time = None |
72 | | - |
73 | | - # Report elapsed time |
74 | | - if self.logger: |
75 | | - self.logger(self.text.format(elapsed_time)) |
76 | | - if self.name: |
77 | | - self.timers[self.name] += elapsed_time |
78 | | - |
79 | | - return elapsed_time |
80 | | - |
81 | | - def __enter__(self) -> "Timer": |
82 | | - """Start a new timer as a context manager""" |
83 | | - self.start() |
84 | | - return self |
85 | | - |
86 | | - def __exit__(self, *exc_info: Any) -> None: |
87 | | - """Stop the context manager timer""" |
88 | | - self.stop() |
0 commit comments