Skip to content

Commit 2be6c87

Browse files
authored
StopWatch class (#631)
1 parent afc98d3 commit 2be6c87

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

debian/changelog

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
python-ev3dev2 (2.0.0~beta4) UNRELEASED; urgency=medium
22

33
[Daniel Walton]
4+
* StopWatch class
45
* Avoid race condition due to poll(None)
56
* MoveDifferential odometry support, tracks robot's (x,y) position
67
* Display support via raspberry pi HDMI

ev3dev2/stopwatch.py

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
"""
2+
A StopWatch class for tracking the amount of time between events
3+
"""
4+
5+
try:
6+
import datetime as dt
7+
micropython = False
8+
except ImportError:
9+
import utime
10+
micropython = True
11+
12+
13+
def get_ticks_ms():
14+
if micropython:
15+
return utime.ticks_ms()
16+
else:
17+
return int(dt.datetime.timestamp(dt.datetime.now()) * 1000)
18+
19+
20+
class StopWatch(object):
21+
22+
def __init__(self, desc=None):
23+
self.desc = desc
24+
self._value = 0
25+
self.start_time = None
26+
self.prev_update_time = None
27+
28+
def __str__(self):
29+
if self.desc is not None:
30+
return self.desc
31+
else:
32+
return self.__class__.__name__
33+
34+
def start(self):
35+
assert self.start_time is None, "%s is already running" % self
36+
self.start_time = get_ticks_ms()
37+
38+
def update(self):
39+
40+
if self.start_time is None:
41+
return
42+
43+
current_time = get_ticks_ms()
44+
45+
if self.prev_update_time is None:
46+
delta = current_time - self.start_time
47+
else:
48+
delta = current_time - self.prev_update_time
49+
50+
self._value += delta
51+
self.prev_update_time = current_time
52+
53+
def stop(self):
54+
55+
if self.start_time is None:
56+
return
57+
58+
self.update()
59+
self.start_time = None
60+
self.prev_update_time = None
61+
62+
def reset(self):
63+
self.stop()
64+
self._value = 0
65+
66+
@property
67+
def value_ms(self):
68+
"""
69+
Returns the value of the stopwatch in milliseconds
70+
"""
71+
self.update()
72+
return self._value
73+
74+
@property
75+
def value_hms(self):
76+
"""
77+
Returns the value of the stopwatch in HH:MM:SS.msec format
78+
"""
79+
self.update()
80+
(hours, x) = divmod(int(self._value), 3600000)
81+
(mins, x) = divmod(x, 60000)
82+
(secs, x) = divmod(x, 1000)
83+
84+
return '%02d:%02d:%02d.%03d' % (hours, mins, secs, x)

0 commit comments

Comments
 (0)