0

I wrote a function to get my PC's memory. But I don't think this is the best way to get it.

def MEMORY():
mem = psutil.virtual_memory()
MEMORYlist = []
for m in mem:
    if m > 100 :
        MEMORYlist.append( str(round(m/1073741824, 3)) + "Gb" )
    else :
        MEMORYlist.append( str(m) + "%")
return MEMORYlist

and the result look like this :

['15.804Gb', '11.303Gb', '28.5%', '4.502Gb', '11.303Gb']

I wonder is there a better way to get same result. Thanks

epinal
  • 1,415
  • 1
  • 13
  • 27
Park Yo Jin
  • 331
  • 1
  • 3
  • 15

1 Answers1

0

Why are you iterating over mem?, it's an object with all the info you may need. You just need to do something like:

import psutil

def get_memory_info():

    mem = psutil.virtual_memory()

    def bytes_to_gb(amount):
        return round(amount / 1e+9, 2)

    data = {"total": bytes_to_gb(mem.total),
            "used": bytes_to_gb(mem.used),
            "available": bytes_to_gb(mem.available),
            "percent": mem.percent
            # Add here whatever data you need
            }

    return data

print(get_memory_info())
epinal
  • 1,415
  • 1
  • 13
  • 27
  • Hi epinal, thansk for your comment but can i ask while you division 1e+9 ? The result not so exactly. I think my result is more exactly. – Park Yo Jin Feb 28 '18 at 16:19
  • @QuangLe the data comes in bytes I just used this conversion https://www.google.com/search?client=ubuntu&channel=fs&q=gb+to+bytes&ie=utf-8&oe=utf-8, you can use your own, it's just an example. Let me know if you need anything else, if not please accept the answer ;-) – epinal Feb 28 '18 at 16:30
  • Is there anyway to check that your code run faster, cost less resource than my cost. I'm sure there is the way to check run time in Python but not sure about resource – Park Yo Jin Mar 01 '18 at 21:23
  • Sure just, add: `start_time = time.time()` `# call the function here` `end_time = time.time()` `print("Time elapsed in milliseconds: %s" % (end_time - start_time))`. However the question wasn't about time, it was about a better way to get the data you need and you lopped somehow over an instance which is wrong in this case. – epinal Mar 02 '18 at 14:56
  • Thanks epinal, i get it ! – Park Yo Jin Mar 04 '18 at 17:25
  • No problem. ;-) – epinal Mar 05 '18 at 16:33