1

I am trying to convert total physical memory into stick value, ie 128gb, 64gb..etc.

if I take the value of total ram from my servers, example 16826298368, and run this code I get and expected output of 16gb. Which is great. But as the memory values increases, it begins to drift.
Example: 134931955712 produces 126GB where 128GB is expected. Example: 67519483904 produces 63GB where 64GB is expected.

So my question is, how can I modify to get the expected output consistently as the value changes? The memory value is provided by a few different bits of code depending on the OS. We use psutil on Solaris for example. psutil.virtual_memory().total

def transform_memory(data):
    for x in ["bytes", " KB", " MB", " GB"]:
        if data < 1024.0:
            return "%3.1f%s" % (math.ceil(data), x)
        data /= 1024.0
    return "%3.1f%s" % (data, " TB")
scott
  • 143
  • 1
  • 2
  • 12
  • Considering that `1GB = 1073741824 bytes`, we have `126 * 1073741824 = 135291469824 bytes` which means that your results are correct and mistakes occur due to integer division. You can check it yourself [here](https://www.convertunits.com/from/GB/to/byte). – Vasilis G. Feb 28 '18 at 15:54
  • Thanks for the info. Looking at the raw data, it seems it is being returned as mebibytes. need to look at the source a bit more. – scott Mar 01 '18 at 18:37

1 Answers1

0

Try this:

import psutil

def bytes2human(n):
    # http://code.activestate.com/recipes/578019
    # >>> bytes2human(10000)
    # '9.8K'
    # >>> bytes2human(100001221)
    # '95.4M'
    symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
    prefix = {}
    for i, s in enumerate(symbols):
        prefix[s] = 1 << (i + 1) * 10
    for s in reversed(symbols):
        if n >= prefix[s]:
            value = float(n) / prefix[s]
            return '%.1f%s' % (value, s)
    return "%sB" % n

total = psutil.disk_usage('/').total
print(total)
print(bytes2human(total))

...prints:

100399730688
93.5G

Since it's a common use case I just added the above to psutil doc: http://psutil.readthedocs.io/en/latest/#bytes-conversion

Giampaolo Rodolà
  • 12,488
  • 6
  • 68
  • 60
  • The issue was not getting it into a human readable format, it was getting it into a commercial readable view. like 64gb 128gb. – scott Mar 01 '18 at 18:36