Merge pull request #279 from robtaylor/robtaylor/liberty-speed
Faster version of liberty_float - gives a 25% to 50% speedup
This commit is contained in:
commit
f6f76f3dc9
|
@ -31,12 +31,15 @@ from collections import defaultdict
|
||||||
|
|
||||||
from typing import Tuple, List, Dict
|
from typing import Tuple, List, Dict
|
||||||
|
|
||||||
|
from math import frexp, log2
|
||||||
|
|
||||||
from . import sizes
|
from . import sizes
|
||||||
from .utils import sortable_extracted_numbers
|
from .utils import sortable_extracted_numbers
|
||||||
|
|
||||||
|
|
||||||
debug = False
|
debug = False
|
||||||
|
|
||||||
|
LOG2_10 = log2(10)
|
||||||
|
|
||||||
class TimingType(enum.IntFlag):
|
class TimingType(enum.IntFlag):
|
||||||
"""
|
"""
|
||||||
|
@ -766,6 +769,15 @@ def liberty_float(f):
|
||||||
>>> liberty_float(1)
|
>>> liberty_float(1)
|
||||||
'1.0000000000'
|
'1.0000000000'
|
||||||
|
|
||||||
|
>>> liberty_float(1e9)
|
||||||
|
'1000000000.0'
|
||||||
|
|
||||||
|
>>> liberty_float(1e10)
|
||||||
|
'1.000000e+10'
|
||||||
|
|
||||||
|
>>> liberty_float(1e15)
|
||||||
|
'1.000000e+15'
|
||||||
|
|
||||||
>>> liberty_float(True)
|
>>> liberty_float(True)
|
||||||
Traceback (most recent call last):
|
Traceback (most recent call last):
|
||||||
...
|
...
|
||||||
|
@ -792,36 +804,25 @@ def liberty_float(f):
|
||||||
|
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
f2 = float(f)
|
r = float(f)
|
||||||
except (ValueError, TypeError):
|
except (ValueError, TypeError):
|
||||||
f2 = None
|
r = None
|
||||||
|
|
||||||
if isinstance(f, bool):
|
if isinstance(f, bool):
|
||||||
f2 = None
|
r = None
|
||||||
|
|
||||||
if f is None or f2 != f:
|
if f is None or r != f:
|
||||||
raise ValueError("%r is not a float" % f)
|
raise ValueError("%r is not a float" % f)
|
||||||
|
|
||||||
WIDTH = len(str(0.0083333333))
|
width = 11
|
||||||
|
|
||||||
s = json.dumps(f)
|
mag = int(frexp(r)[1]/LOG2_10)
|
||||||
if 'e' in s:
|
if mag > 9:
|
||||||
a, b = s.split('e')
|
return f'%{width}e' % r
|
||||||
if '.' not in a:
|
if mag < 0:
|
||||||
a += '.'
|
return f"%{width+1}.{width-1}f" % r
|
||||||
while len(a)+len(b)+1 < WIDTH:
|
|
||||||
a += '0'
|
|
||||||
s = "%se%s" % (a, b)
|
|
||||||
elif '.' in s:
|
|
||||||
while len(s) < WIDTH:
|
|
||||||
s += '0'
|
|
||||||
else:
|
else:
|
||||||
if len(s) < WIDTH:
|
return f"%{width+1}.{width-mag-1}f" % r
|
||||||
s += '.'
|
|
||||||
while len(s) < WIDTH:
|
|
||||||
s += '0'
|
|
||||||
return s
|
|
||||||
|
|
||||||
|
|
||||||
LIBERTY_ATTRIBUTE_TYPES = {
|
LIBERTY_ATTRIBUTE_TYPES = {
|
||||||
'boolean': liberty_bool,
|
'boolean': liberty_bool,
|
||||||
|
|
Loading…
Reference in New Issue