-
Notifications
You must be signed in to change notification settings - Fork 26
/
time.py
56 lines (43 loc) · 1.24 KB
/
time.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import time
from contextlib import ContextDecorator
class Timer(ContextDecorator):
"""Timer ContextManager and Decorator.
Examples:
>>> import time
>>>
>>> from tools.trace import Timer
>>>
>>> with Timer("examples"):
>>> time.sleep(1)
>>> import time
>>>
>>> from tools.trace import Timer
>>>
>>>
>>> @Timer("sleep")
>>> def sleep(t: int = 1) -> None:
>>> time.sleep(t)
>>>
>>>
>>> sleep(1)
"""
def __init__(self, name: str) -> None:
"""Initialize Timer.
Args:
name (str): Log name
"""
super().__init__()
self.name = name
def __enter__(self) -> None:
"""Run when enter ContextManager or Decorator."""
self.start = time.time()
def __exit__(self, *exc: object) -> None:
"""Run when exit ContextManager or Decoraotr."""
self.end = time.time()
from tools.logger import Logger
logger = Logger(self.name)
logger.debug("executed in %f ms", self._duration * 1_000)
@property
def _duration(self) -> float:
"""Return duration in seconds."""
return self.end - self.start