Skip to content

Commit bb99238

Browse files
authored
Optimize naturalsize algorithm by using math.log (#253)
1 parent b818dbf commit bb99238

File tree

1 file changed

+5
-11
lines changed

1 file changed

+5
-11
lines changed

src/humanize/filesize.py

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
from __future__ import annotations
44

5+
from math import log
6+
57
suffixes = {
68
"decimal": (
79
" kB",
@@ -83,11 +85,7 @@ def naturalsize(
8385
suffix = suffixes["decimal"]
8486

8587
base = 1024 if (gnu or binary) else 1000
86-
if isinstance(value, str):
87-
bytes_ = float(value)
88-
else:
89-
bytes_ = value
90-
88+
bytes_ = float(value)
9189
abs_bytes = abs(bytes_)
9290

9391
if abs_bytes == 1 and not gnu:
@@ -96,10 +94,6 @@ def naturalsize(
9694
if abs_bytes < base:
9795
return f"{int(bytes_)}B" if gnu else f"{int(bytes_)} Bytes"
9896

99-
for i, s in enumerate(suffix, 2):
100-
unit = base**i
101-
if abs_bytes < unit:
102-
break
103-
104-
ret: str = format % (base * (bytes_ / unit)) + s
97+
exp = int(min(log(abs_bytes, base), len(suffix)))
98+
ret: str = format % (bytes_ / (base**exp)) + suffix[exp - 1]
10599
return ret

0 commit comments

Comments
 (0)