mathoudebine / turing-smart-screen-python

Unofficial Python system monitor and library for small IPS USB-C displays like Turing Smart Screen or XuanFang
GNU General Public License v3.0
1.05k stars 174 forks source link

Proper units for RAM (and disks) #449

Open orzel opened 7 months ago

orzel commented 7 months ago

While for disk, the kilo/mega/giga are usually power of 1000, for RAM, it's usually power of 1024 that are used.

The code in library/stats.py:class Memory uses / 1000000 everywhere. May i suggest to use instead 1024**2 ?

Another, slightly related problem, is that the source hardcode the suffixes (for ex 'M' for ram, 'G' for disk), but that's hardly generic enough. For my use case, ram is in the hundred of G range, and disks are in several dozens of TB.

There's a typical function to handle this (found all around the web):

suffixes = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']
def human_number(nbytes, thousand=1000):
    """
    Take an optional argument giving the multiple as a power of 1000.
    For example human_number(2000) == human_number(2,1)
    By default, use power of 1000, but you can use thousand=1024 for a
    more 'computer-friendly' way of doing.
    >>> human_number(5)
    '5'
    >>> human_number(3*1000)
    '3 k'
    >>> human_number(1000*1000*1000*1000)
    '1 T'
    >>> human_number(1000*1000*1000*1000*1000*1000*1000*1000)
    '1000 Z' 
    >>> human_number(999*1000*1000*1000)
    '999 G'

    power of 1024
    >>> human_number(3*1024, 1024)
    '3 k'
    >>> human_number(5*1024*1024, 1024)
    '5 M'
    """
    assert(type(nbytes)==int)
    if nbytes == 0: return '0'
    i = 0
    while nbytes >= thousand and i < len(suffixes)-1:
        nbytes /= float(thousand)
        i += 1
    f = ('%.2f' % nbytes).rstrip('0').rstrip('.').rstrip(' ')
    if i==0:
        return "%s"%f
    else:
        return '%s %s' % (f, suffixes[i])

(note it includes doctests)

I understand this can't be used as is, because the code in library/stats.py expects the value and unit in two different variables, but this can easily be adapted.

So typically you would use human_number(size, 1000) for disk-related sizes, and human_number(size, 1024) for ram stuff.

mathoudebine commented 7 months ago

Thanks for letting me know, I will create a PR for the Memory power of 1024 I agree it would be interesting to have an automatic value/unit for the Disk & RAM values, like it is done for Network metrics

mathoudebine commented 7 months ago

Memory power of 1024 is now fixed, I will keep your issue open for the automatic value/unit