-
Notifications
You must be signed in to change notification settings - Fork 501
Expand file tree
/
Copy pathstopwatch.py
More file actions
91 lines (78 loc) · 2.53 KB
/
stopwatch.py
File metadata and controls
91 lines (78 loc) · 2.53 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import time
import datetime
class Stopwatch:
"""A stopwatch simulator with functions start, stop, lap, and reset."""
__startTime__ = None
__currentLap__ = 0
laps = []
summary = None
state = "Stopped"
def __init__(self, precision=None):
if precision:
self.__precision__ = precision
else:
# Default to tenths of a second.
self.__precision__ = 1
def start(self):
# Start the stopwatch.
if not self.state == "Stopped":
print("Stopwatch is already running.")
return None
self.__startTime__ = time.time()
self.state = "Started"
def lap(self):
# Start tracking a new lap.
self.__update__()
self.laps.append(self.__currentLap__)
self.__currentLap__ = 0
self.__startTime__ = time.time()
self.__update__()
def stop(self):
# Stop/Pause the stopwatch without clearing it.
if self.state == "Stopped":
print("Stopwatch isn't running.")
else:
self.__update__()
self.state = "Stopped"
def reset(self):
# Reset the entire stopwatch back to zero.
self.__startTime__ = None
self.__currentLap__ = 0
self.laps = []
self.summary = None
self.state = "Stopped"
def __update__(self):
# Internal function to update stopwatch summary.
now = time.time()
lapCounter = 1
lapTime = 0
lapSummary = ""
for lap in self.laps:
# Tally the laps into the total laptime.
lapTime = round(lapTime + lap, self.__precision__)
# Generate a pretty summary.
lapSummary += (
"\nLap "
+ str(lapCounter)
+ ": "
+ str(datetime.timedelta(seconds=round(lap, self.__precision__))).rjust(
14 - len(str(lapCounter))
)
)
lapCounter += 1
if not self.state == "Stopped":
self.__currentLap__ += now - self.__startTime__
totalTime = lapTime + self.__currentLap__
self.summary = (
"Total time: "
+ str(
datetime.timedelta(seconds=round(totalTime, self.__precision__))
).rjust(8)
+ lapSummary
+ "\nCurrent Lap: "
+ str(
datetime.timedelta(
seconds=round(self.__currentLap__, self.__precision__)
)
).rjust(7)
)