Sometimes, we want to get current CPU and RAM usage in Python.
In this article, we’ll look at how to get current CPU and RAM usage in Python.
How to get current CPU and RAM usage in Python?
To get current CPU and RAM usage in Python, we can use the psutil
module.
To install it, we run:
pip install psutil
Then we write:
import psutil
print(psutil.cpu_percent())
print(psutil.virtual_memory())
print(dict(psutil.virtual_memory()._asdict()))
print(psutil.virtual_memory().percent)
print(psutil.virtual_memory().available * 100 / psutil.virtual_memory().total)
to get the percentage of CPU used with cpu_percent
.
virtual_memory
gets the amount of available virtual memory and how much of it is used.
We can call _asdict
on the object returned by virtual_memory
to convert it to a dictionary.
percent
, available
, and total
returns the percent of virtual memory used, amount of virtual memory available in bytes, and total virtual memory available in bytes respectively.
Therefore, we get something like:
0.0
svmem(total=27328045056, available=21079855104, percent=22.9, used=6097809408, free=9938751488, active=4543451136, inactive=8950083584, buffers=1948196864, cached=9343287296, shared=12705792, slab=3136671744)
{'total': 27328045056, 'available': 21079855104, 'percent': 22.9, 'used': 6097809408, 'free': 9938751488, 'active': 4543451136, 'inactive': 8950083584, 'buffers': 1948196864, 'cached': 9343287296, 'shared': 12705792, 'slab': 3136671744}
22.9
77.13634495553431
Conclusion
To get current CPU and RAM usage in Python, we can use the psutil
module.