-
Notifications
You must be signed in to change notification settings - Fork 5
/
util.py
66 lines (59 loc) · 2.21 KB
/
util.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
'''Util.py implements some python-generic utilities (not math-related utils
which are implemented in mathutil.py
'''
import time
class Timer:
'''
class Timer implements some sugar functions that works like a stopwatch.
timer.reset() resets the watch
timer.lap() returns the time elapsed since the last lap() call
timer.total() returns the total time elapsed since the last reset
'''
def __init__(self, template = '{0}h{1}m{2:.2f}s'):
"""Initializes a timer.
Input:
template: (optional) a template string that can be used to format
the timer. Inside the string, use {0} to denote the hour, {1}
to denote the minute, and {2} to denote the seconds. Default
'{0}h{1}m{2:.2f}s'
"""
self._total = time.time()
self._lap = time.time()
if template:
self._template = template
def _format(self, t):
"""format the time value according to the template
"""
hour = int(t / 3600.0)
t = t % 3600.0
minute = int (t / 60)
t = t % 60
return self._template.format(hour,minute,t)
def reset(self):
"""Press the reset button on the timer
"""
self._total = time.time()
self._lap = time.time()
def lap(self, use_template = True):
"""Report the elapsed time of the current lap, and start counting the
next lap.
Input:
use_template: (optional) if True, returns the time as a formatted
string. Otherwise, return the real-valued time. Default True.
"""
diff = time.time() - self._lap
self._lap = time.time()
if use_template:
return self._format(diff)
else:
return diff
def total(self, use_template = True):
"""Report the total elapsed time of the timer.
Input:
use_template: (optional) if True, returns the time as a formatted
string. Otherwise, return the real-valued time. Default True.
"""
if use_template:
return self._format(time.time() - self._total)
else:
return time.time() - self._total