Skip to content

Commit 7acbbe1

Browse files
authored
Merge pull request #97 from robotpy/looptimer
Add LoopTimer object for measuring the performance of robot loops
2 parents 4065071 + af8805f commit 7acbbe1

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

docs/robotpy_ext.misc.rst

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,15 @@ robotpy_ext.misc.asyncio_policy module
99
:undoc-members:
1010
:show-inheritance:
1111

12+
robotpy_ext.misc.looptimer module
13+
---------------------------------------
14+
15+
.. automodule:: robotpy_ext.misc.looptimer
16+
:members:
17+
:undoc-members:
18+
:show-inheritance:
19+
20+
1221
robotpy_ext.misc.precise_delay module
1322
-------------------------------------
1423

robotpy_ext/misc/looptimer.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
2+
import math
3+
import wpilib
4+
5+
_getFPGATimestamp = wpilib.Timer.getFPGATimestamp
6+
7+
class LoopTimer:
8+
'''
9+
A utility class that measures the number of loops that a robot program
10+
executes, and computes the min/max/average period for loops in the last
11+
second.
12+
13+
Example usage::
14+
15+
class Robot(wpilib.IterativeRobot):
16+
17+
def teleopInit(self):
18+
self.loop_timer = LoopTimer(self.logger)
19+
20+
def teleopPeriodic(self):
21+
self.loop_timer.measure()
22+
23+
Mainly intended for debugging purposes to measure how much lag.
24+
'''
25+
26+
def __init__(self, logger):
27+
self.logger = logger
28+
self.timer = wpilib.Timer()
29+
self.timer.start()
30+
31+
self.reset()
32+
33+
def reset(self):
34+
self.timer.reset()
35+
36+
self.start = self.last = _getFPGATimestamp()
37+
self.min_time = math.inf
38+
self.max_time = -1
39+
self.loops = 0
40+
41+
42+
def measure(self):
43+
'''
44+
Computes loop performance information and periodically dumps it to
45+
the info logger.
46+
'''
47+
48+
# compute min/max/count
49+
now = _getFPGATimestamp()
50+
diff = now - self.last
51+
self.min_time = min(self.min_time, diff)
52+
self.max_time = max(self.max_time, diff)
53+
54+
self.loops += 1
55+
self.last = now
56+
57+
if self.timer.hasPeriodPassed(1):
58+
self.logger.info("Loops: %d; min: %.3f; max: %.3f; period: %.3f; avg: %.3f",
59+
self.loops, self.min_time, self.max_time, now - self.start,
60+
(now - self.start) / self.loops)
61+
62+
self.min_time = math.inf
63+
self.max_time = -1
64+
self.start = now
65+
self.loops = 0

0 commit comments

Comments
 (0)