-
Notifications
You must be signed in to change notification settings - Fork 12
/
timer.py
60 lines (50 loc) · 1.48 KB
/
timer.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
57
58
59
60
from timeit import default_timer
from datetime import timedelta
class Timer:
"""Timer class.
Examples:
>>> import time
>>> t = Timer()
>>> t.start()
>>> time.sleep(1)
>>> t.stop()
>>> t.interval > 0.8 and t.interval < 1.2
True
>>> with Timer() as t:
... time.sleep(1)
>>> t.interval > 0.8 and t.interval < 1.2
True
>>> "Time elapsed {}".format(t) #doctest: +ELLIPSIS
'Time elapsed 1...'
"""
def __init__(self):
self._timer = default_timer
self._interval = 0
self.running = False
def __enter__(self):
self.start()
return self
def __exit__(self, *args):
self.stop()
def __str__(self):
return "{:0.4f}".format(self.interval)
def start(self):
"""Start the timer."""
self.init = self._timer()
self.running = True
def stop(self):
"""Stop the timer. Calculate the interval in seconds."""
self.end = self._timer()
try:
self._interval = self.end - self.init
self.running = False
except AttributeError:
raise ValueError(
"Timer has not been initialized: use start() or the contextual form with Timer() as t:"
)
@property
def interval(self):
if self.running:
raise ValueError("Timer has not been stopped, please use stop().")
else:
return self._interval