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
92
93
94
95
96
97
98
99
100
101
|
"""Miscellanious utility functions that don't fit anywhere."""
def format_float(num, numplaces):
if num is None:
return '(None)'
if abs(round(num, numplaces) - round(num, 0)) == 0.0:
return '%.0f' % float(num)
else:
return ('%.' + str(numplaces) + 'f') % round(float(num), numplaces)
class TimeUnit(object):
"""Class that represents a certain time unit."""
def nsec_to_native(self, time):
raise NotImplementedError
def native_to_nsec(self, time):
raise NotImplementedError
class NanoSec(TimeUnit):
def __str__(self):
return 'ns'
def nsec_to_native(self, time):
return time
def native_to_nsec(self, time):
return time
class MicroSec(TimeUnit):
def __str__(self):
return 'us'
def nsec_to_native(self, time):
if time is None: return time
return time / 1000.0
def native_to_nsec(self, time):
if time is None: return time
return time * 1000.0
class MilliSec(TimeUnit):
def __str__(self):
return 'ms'
def nsec_to_native(self, time):
if time is None: return time
return time / 1000000.0
def native_to_nsec(self, time):
if time is None: return time
return time * 1000000.0
class Sec(TimeUnit):
def __str__(self):
return 's'
def nsec_to_native(self, time):
if time is None: return time
return time / 1000000000.0
def native_to_nsec(self, time):
if time is None: return time
return time * 1000000000.0
def parse_time(text):
# perhaps the user didn't put a space between the number and
# the time unit
for i, char in enumerate(text):
if char == ' ':
break
elif char.isalpha():
text = text[0:i] + ' ' + text[i:]
break
tokens = text.split()
if len(tokens) > 2 or len(tokens) == 0:
raise ValueError
unit = None
if len(tokens) == 2:
unit = parse_unit(tokens[1])
else:
unit = MilliSec()
return unit.native_to_nsec(float(tokens[0]))
def parse_unit(expr):
expr = expr.strip().lower()
if expr == 'ns' or expr == 'nsec' or expr == 'nsecs' or expr == 'nanosec' or expr == 'nanosecs':
return NanoSec()
elif expr == 'us' or expr == 'usec' or expr == 'usecs' or expr == 'microsec' or expr == 'microsecs':
return MicroSec()
elif expr == 'ms' or expr == 'msec' or expr == 'msecs' or expr == 'millisec' or expr == 'millisecs':
return MilliSec()
elif expr == 's' or expr == 'sec' or expr == 'secs' or expr == 'second' or expr == 'seconds':
return Sec()
else:
raise ValueError
|