Skip to content

Commit 3e151f3

Browse files
committed
Split code into separate file
1 parent 362d6fa commit 3e151f3

File tree

2 files changed

+67
-63
lines changed

2 files changed

+67
-63
lines changed

codetiming/__init__.py

Lines changed: 3 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -4,85 +4,25 @@
44
55
1. As a **class**:
66
7-
```python
87
t = Timer(name="class")
98
t.start()
109
# Do something
1110
t.stop()
12-
```
1311
1412
2. As a **context manager**:
1513
16-
```python
1714
with Timer(name="context manager"):
1815
# Do something
19-
```
2016
2117
3. As a **decorator**:
2218
23-
```python
2419
@Timer(name="decorator")
2520
def stuff():
2621
# Do something
27-
```
2822
"""
2923

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
3426

27+
# Versioning is handled by bump2version
3528
__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()

codetiming/_timer.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
"""Definition of Timer
2+
3+
See help(codetiming) for quick instructions, and
4+
https://pypi.org/project/codetiming/ for more details
5+
"""
6+
7+
# Standard library imports
8+
from contextlib import ContextDecorator
9+
from dataclasses import dataclass, field
10+
import time
11+
from typing import Any, Callable, ClassVar, Dict, Optional
12+
13+
14+
class TimerError(Exception):
15+
"""A custom exception used to report errors in use of Timer class"""
16+
17+
18+
@dataclass
19+
class Timer(ContextDecorator):
20+
"""Time your code using a class, context manager, or decorator"""
21+
22+
timers: ClassVar[Dict[str, float]] = dict()
23+
name: Optional[str] = None
24+
text: str = "Elapsed time: {:0.4f} seconds"
25+
logger: Optional[Callable[[str], None]] = print
26+
_start_time: Optional[float] = field(default=None, init=False, repr=False)
27+
28+
def __post_init__(self) -> None:
29+
"""Initialization: add timer to dict of timers"""
30+
if self.name:
31+
self.timers.setdefault(self.name, 0)
32+
33+
def start(self) -> None:
34+
"""Start a new timer"""
35+
if self._start_time is not None:
36+
raise TimerError(f"Timer is running. Use .stop() to stop it")
37+
38+
self._start_time = time.perf_counter()
39+
40+
def stop(self) -> float:
41+
"""Stop the timer, and report the elapsed time"""
42+
if self._start_time is None:
43+
raise TimerError(f"Timer is not running. Use .start() to start it")
44+
45+
# Calculate elapsed time
46+
elapsed_time = time.perf_counter() - self._start_time
47+
self._start_time = None
48+
49+
# Report elapsed time
50+
if self.logger:
51+
self.logger(self.text.format(elapsed_time))
52+
if self.name:
53+
self.timers[self.name] += elapsed_time
54+
55+
return elapsed_time
56+
57+
def __enter__(self) -> "Timer":
58+
"""Start a new timer as a context manager"""
59+
self.start()
60+
return self
61+
62+
def __exit__(self, *exc_info: Any) -> None:
63+
"""Stop the context manager timer"""
64+
self.stop()

0 commit comments

Comments
 (0)