-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimer.py
More file actions
74 lines (55 loc) · 2.04 KB
/
timer.py
File metadata and controls
74 lines (55 loc) · 2.04 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"""
Code originally based on a response in
https://stackoverflow.com/questions/7370801/measure-time-elapsed-in-python
"""
import time
from timeit import default_timer
from typing import Final
class Timer:
_start: float
_elapsed: str
def __init__(self) -> None:
self._start = default_timer()
self._elapsed = ''
def __enter__(self) -> 'Timer':
self._start = default_timer()
self._elapsed = ''
return self
def __exit__(self, the_type, the_value, the_traceback) -> None:
self.set_elapsed()
def restart(self) -> None:
self._start = default_timer()
def set_elapsed(self) -> None:
duration: Final = default_timer() - self._start
_, reminder_of_s = divmod(duration, 1)
ds: Final = 10*round(reminder_of_s, 1) # if we want ds
# cs: Final = 100*round(remainder_of_s, 2) # if we want cs
# ms: Final = 1000*round(remainder_of_s, 3) # if we want ms
m, s = divmod(duration, 60)
h, m = divmod(m, 60)
# print(f'» types of h, m, s, and cs are {type(h)}, {type(m)}, {type(s)}, and {type(s)}') # all <class 'float'>
# print(f'» cs is {cs}')
h = int(h)
m = int(m)
s = int(s)
# print(f'» types of h, m, s, and cs are {type(h)}, {type(m)}, {type(s)}, and {type(s)}') # all <class 'int'>
if h > 0:
self._elapsed = f"{h} hours {m} minutes {s}.{ds:01g} seconds"
elif m > 0:
self._elapsed = f"{m} minutes {s}.{ds:01g} seconds"
else:
self._elapsed = f'{s}.{ds:01g} seconds'
def elapsed(self) -> str:
self.set_elapsed()
return self._elapsed
def main():
timer: Final = Timer()
time.sleep(.12345678) # 61.2345678)
print(f'First `sleep` took {timer.elapsed()}')
timer.restart()
print(f'After `restart` {timer.elapsed()} have passed')
with Timer() as timer_for_context:
time.sleep(.2468)
print(f'After context {timer_for_context.elapsed()} have passed')
if __name__ == '__main__':
main()