How to get current CPU and RAM usage in Python? How to get current CPU and RAM usage in Python? python python

How to get current CPU and RAM usage in Python?

The psutil library gives you information about CPU, RAM, etc., on a variety of platforms:

psutil is a module providing an interface for retrieving information on running processes and system utilization (CPU, memory) in a portable way by using Python, implementing many functionalities offered by tools like ps, top and Windows task manager.

It currently supports Linux, Windows, OSX, Sun Solaris, FreeBSD, OpenBSD and NetBSD, both 32-bit and 64-bit architectures, with Python versions from 2.6 to 3.5 (users of Python 2.4 and 2.5 may use 2.1.3 version).

Some examples:

#!/usr/bin/env pythonimport psutil# gives a single float valuepsutil.cpu_percent()# gives an object with many fieldspsutil.virtual_memory()# you can convert that object to a dictionary dict(psutil.virtual_memory()._asdict())# you can have the percentage of used RAMpsutil.virtual_memory().percent79.2# you can calculate percentage of available memorypsutil.virtual_memory().available * 100 / psutil.virtual_memory().total20.8

Here's other documentation that provides more concepts and interest concepts:

Use the psutil library. On Ubuntu 18.04, pip installed 5.5.0 (latest version) as of 1-30-2019. Older versions may behave somewhat differently.You can check your version of psutil by doing this in Python:

from __future__ import print_function  # for Python2import psutilprint(psutil.__versi‌​on__)

To get some memory and CPU stats:

from __future__ import print_functionimport psutilprint(psutil.cpu_percent())print(psutil.virtual_memory())  # physical memory usageprint('memory % used:', psutil.virtual_memory()[2])

The virtual_memory (tuple) will have the percent memory used system-wide. This seemed to be overestimated by a few percent for me on Ubuntu 18.04.

You can also get the memory used by the current Python instance:

import osimport psutilpid = os.getpid()python_process = psutil.Process(pid)memoryUse = python_process.memory_info()[0]/2.**30  # memory use in GB...I thinkprint('memory use:', memoryUse)

which gives the current memory use of your Python script.

There are some more in-depth examples on the pypi page for psutil.

Only for Linux: One-liner for the RAM usage with only stdlib dependency:

import ostot_m, used_m, free_m = map(int, os.popen('free -t -m').readlines()[-1].split()[1:])

edit: specified solution OS dependency