turing-smart-screen-python
turing-smart-screen-python copied to clipboard
Proper units for RAM (and disks)
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.