-
Notifications
You must be signed in to change notification settings - Fork 9
/
timer.py
54 lines (45 loc) · 1.85 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
import time
# A simple, multi-purpose timer class to manage time steps in loops, control execution times, etc.
class Timer:
# Constructor starts the timer at instantiation
def __init__(self):
self.paused = False
self.pauseInitTime = []
self.pauseElapsed = 0
self.initTime = time.time()
# Method resets the timer initial time to current time
def reset(self):
self.paused = False
self.pauseInitTime = []
self.pauseElapsed = 0
self.initTime = time.time()
# Method allows to pause the timer
def pause(self):
self.pauseInitTime = time.time()
self.paused = True
# Method allows to resume counting time following call to Timer.pause()
def resume(self):
if self.paused:
self.pauseElapsed += time.time() - self.pauseInitTime
self.paused = False
else:
print "Timer.resume() called without prior call to Timer.pause()"
# Method returns the time elapsed since instantiation or last reset minus sum of paused time
def getElapsed(self):
if self.paused:
return self.pauseInitTime - self.initTime - self.pauseElapsed
else:
return time.time() - self.initTime - self.pauseElapsed
# Method sleeps until elapsed time reaches delay argument then resets the timer
# Useful to control fixed time step in loops.
def sleepToElapsed(self, delay):
if self.getElapsed() < delay:
time.sleep(delay - self.getElapsed())
self.reset()
# Method returns True if elapsed time is within delay argument.
# Useful to control execution of while loops for a fixed time duration.
def isWithin(self, delay):
if self.getElapsed() <= delay:
return True
else:
return False