"""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