提交 5a1b7133 编写于 作者: A Amador Pahim

DataSize: simplify __init__

Instead of using regex to parse the `data`, let's use a simpler and more
performatic version witch just handles the last character to figure out
the unit.

Before this patch:

>>> timeit.timeit('data_structures.DataSize("1M").b',
                  setup='from avocado.utils import data_structures',
                  number=1000000)
>>> 2.988218069076538

After this patch:

>>> timeit.timeit('data_structures.DataSize("1M").b',
                  setup='from avocado.utils import data_structures',
                  number=1000000)
>>> 2.0695440769195557
Signed-off-by: NAmador Pahim <apahim@redhat.com>
上级 ea947b23
......@@ -22,7 +22,6 @@ avocado core code or plugins.
"""
import re
import sys
import math
......@@ -269,22 +268,28 @@ class DataSize(object):
('t', 1099511627776)]) # 2**40
def __init__(self, data):
pattern = r"^(\d+)([bkmgt])?$" # Number and optional string
match = re.match(pattern, data, re.IGNORECASE)
try:
norm_size = data.strip().lower()
last = norm_size[-1]
if last.isdigit():
self._value = int(norm_size)
self._unit = 'b'
elif last in self.MULTIPLIERS:
self._value = int(norm_size[:-1])
self._unit = last
else:
raise ValueError
if match is None:
raise InvalidDataSize('String not in size+unit format (i.e. '
'"10M", "100k", ...)')
if self._value < 0:
raise ValueError
self._value, unit = match.groups()
if unit is None:
self._unit = 'b'
else:
self._unit = unit.lower()
except ValueError:
raise InvalidDataSize('String not in size + unit format (i.e. '
'"10M", "100k", ...)')
@property
def value(self):
return int(self._value)
return self._value
@property
def unit(self):
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册