diff options
author | hut <hut@lavabit.com> | 2010-06-24 22:41:20 +0200 |
---|---|---|
committer | hut <hut@lavabit.com> | 2010-06-24 22:41:20 +0200 |
commit | 7bc8b3fc32b44a8db8bfb321423a1bb7718350ab (patch) | |
tree | 1d5e08a6565640acf7ed4f2ad7c3fc3089c45d56 /ranger | |
parent | 20ab9343ae45320eb29f96ddb66b30148be2aa7f (diff) | |
download | ranger-7bc8b3fc32b44a8db8bfb321423a1bb7718350ab.tar.gz |
ext.human_readable: more efficient implementation
plus unit tests and benchmark.
Diffstat (limited to 'ranger')
-rw-r--r-- | ranger/ext/human_readable.py | 53 |
1 files changed, 34 insertions, 19 deletions
diff --git a/ranger/ext/human_readable.py b/ranger/ext/human_readable.py index beeaf6d3..35dbc35e 100644 --- a/ranger/ext/human_readable.py +++ b/ranger/ext/human_readable.py @@ -13,24 +13,39 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. -import math - -ONE_KB = 1024 -UNITS = 'BKMGTP' -MAX_EXPONENT = len(UNITS) - 1 - def human_readable(byte, seperator=' '): - if not byte: - return '0' - - exponent = int(math.log(byte, 2) / 10) - flt = round(float(byte) / (1 << (10 * exponent)), 2) + """ + Convert a large number of bytes to an easily readable format. - if exponent > MAX_EXPONENT: - return '>9000' # off scale - - if int(flt) == flt: - return '%.0f%s%s' % (flt, seperator, UNITS[exponent]) - - else: - return '%.2f%s%s' % (flt, seperator, UNITS[exponent]) + >>> human_readable(54) + "54 B" + >>> human_readable(1500) + "1.46 K" + >>> human_readable(2 ** 20 * 1023) + "1023 M" + """ + if byte <= 0: + return '0' + if byte < 2**10: + return '%d%sB' % (byte, seperator) + if byte < 2**10 * 1000: + return '%.3g%sK' % (byte / 2**10.0, seperator) + if byte < 2**20: + return '%.4g%sK' % (byte / 2**10.0, seperator) + if byte < 2**20 * 1000: + return '%.3g%sM' % (byte / 2**20.0, seperator) + if byte < 2**30: + return '%.4g%sM' % (byte / 2**20.0, seperator) + if byte < 2**30 * 1000: + return '%.3g%sG' % (byte / 2**30.0, seperator) + if byte < 2**40: + return '%.4g%sG' % (byte / 2**30.0, seperator) + if byte < 2**40 * 1000: + return '%.3g%sT' % (byte / 2**40.0, seperator) + if byte < 2**50: + return '%.4g%sT' % (byte / 2**40.0, seperator) + if byte < 2**50 * 1000: + return '%.3g%sP' % (byte / 2**50.0, seperator) + if byte < 2**60: + return '%.4g%sP' % (byte / 2**50.0, seperator) + return '>9000' |