Last active
December 15, 2015 03:29
-
-
Save jrenner/5195216 to your computer and use it in GitHub Desktop.
A script for testing glances' autoUnit function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
__author__ = 'jrenner' | |
import random | |
import sys | |
""" | |
This script is useful for testing the autoUnit function. It is not guaranteed | |
to be the same as in glances.py. You may need to copy and paste the exact | |
code you want to test from glances.py | |
""" | |
def autoUnit(val): | |
""" | |
Convert val to string and concatenate the good unit | |
Exemples: | |
960 -> 960 | |
142948 -> 143K | |
560745673 -> 561M | |
... | |
""" | |
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') | |
prefix = { | |
'Y': 1208925819614629174706176, | |
'Z': 1180591620717411303424, | |
'E': 1152921504606846976, | |
'P': 1125899906842624, | |
'T': 1099511627776, | |
'G': 1073741824, | |
'M': 1048576, | |
'K': 1024 | |
} | |
for key in reversed(symbols): | |
value = float(val) / prefix[key] | |
if value > 1: | |
fixed_decimal_places = 0 | |
if value < 100: | |
fixed_decimal_places = 1 | |
if value < 10: | |
fixed_decimal_places = 2 | |
val_string = "{0:.%df}{1}" % fixed_decimal_places | |
if key in 'YZEPTG': | |
return val_string.format(value, key) | |
else: | |
return "{0:.0f}{1}".format(value, key) | |
return "{0!s}".format(val) | |
test_cases = [ | |
] | |
for i in range(24): | |
lo = i * 10 ** i | |
hi = i * 10 ** (i + 1) | |
test_cases.append(random.randint(lo, hi)) | |
def test(): | |
for case in test_cases: | |
print "CASE: {0:<26} RESULT: {1:>12}".format(case, autoUnit(case)) | |
test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment