-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimer.py
71 lines (50 loc) · 1.81 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
61
62
63
64
65
66
67
68
69
70
71
""" Timer Class """
import time
class Error(Exception):
""" Base class for Timer Exceptions """
pass
class TimerStartError(Error):
def __init__(self, message):
self.message = message
class TimerEndError(Error):
def __init__(self, message):
self.message = message
class Timer:
def __init__(self, text="The task took a time of: {:0.6f} seconds"):
""" Init the variables """
self.start_time = None
self.text = text
def start(self):
""" Start a new timer """
try:
if self.start_time is not None:
raise TimerStartError("Timer is running. Use .stop() to stop it")
self.start_time = time.perf_counter()
except TimerStartError as tse:
print()
print(tse.message)
exit(0)
def stop_print(self):
""" Stop the timer, and report the elapsed time """
try:
if self.start_time is None:
raise TimerEndError("Timer is not running. Use .start() to start it")
elapsed_time = time.perf_counter() - self.start_time
self.start_time = None
print(self.text.format(elapsed_time))
except TimerEndError as tee:
print()
print(tee.message)
exit(0)
def stop_time(self):
""" Stop the timer, and report the elapsed time """
try:
if self.start_time is None:
raise TimerEndError("Timer is not running. Use .start() to start it")
elapsed_time = time.perf_counter() - self.start_time
self.start_time = None
return elapsed_time
except TimerEndError as tee:
print()
print(tee.message)
exit(0)