카테고리 없음

Python: Checking System RAM/CPU/Disk Usage

광82 2023. 9. 26. 13:15
반응형

This succinct, practical article shows you how to programmatically check RAM (memory), CPU, and disk usage in Python. You can get the job done painlessly by using a package called psutil. Install it by performing the following command:

Advertisements
pip install psutil

Let’s see some code examples for more clarity.

Checking RAM usage

To get information about memory usage, you can use the psutil.virtual_memory() function, which returns a named tuple with fields such as total, available, percent, used, free, etc. These fields represent the amount of memory in bytes or the percentage of memory used.

Advertisements

Example:

import psutil

try:
    ram_info = psutil.virtual_memory()
    print(f"Total: {ram_info.total / 1024 / 1024 / 1024:.2f} GB")
    print(f"Available: {ram_info.available / 1024 / 1024 / 1024:.2f} GB")
    print(f"Used: {ram_info.used / 1024 / 1024 / 1024:.2f} GB")
    print(f"Percentage usage: {ram_info.percent}%")
except FileNotFoundError:
    print("Ram info not available on this system")

Output (on my machine):

Total: 16.00 GB
Available: 6.99 GB
Used: 8.42 GB
Percentage usage: 56.3%

The units are bytes. You can get the results in kilobytes, megabytes, and gigabytes by dividing each of them by 1024, 1024 * 1024, and 1024 * 1024 * 1024, respectively.

Checking CPU usage

In order to check CPU usage, you can use the psutil.cpu_percent() function, which returns a float representing the current system-wide CPU utilization as a percentage. You can also use the psutil.cpu_freq() to get the information about the CPU frequency.

Example:

import psutil

try:
    cpu_percent = psutil.cpu_percent()
    print(f"Percentage usage: {cpu_percent}%")
    
    # CPU frequency
    cpu_info = psutil.cpu_freq()
    print(f"Current frequency: {cpu_info.current:.2f} Mhz")
    print(f"Minimum frequency: {cpu_info.min:.2f} Mhz")
    print(f"Maximum frequency: {cpu_info.max:.2f} Mhz")
   
except FileNotFoundError:
    print("CPU info not available on this system")

On Mac M1 and M2 machines, some functions, such as psutil.cpu_freq() may not work properly or raise an exception due to incompatible architectures or lack of support from Apple’s APIs. This is a known issue that has not been resolved yet. Thus, you should always use try...except to handle errors gracefully.

Checking disk usage

The psutil.disk_usage(path) function can help you determine the amount of storage that has been used. It returns a named tuple with fields such as total, used, free and percent. These fields represent the amount of disk space in bytes or the percentage of disk space used for a given path (such as ‘/’ for the root directory). The results are in bytes. You can turn one to GB just by dividing it by 1024 * 1024 * 1024.

Example:

import psutil

try:
    disk_info = psutil.disk_usage("/")
    print(f"Total: {disk_info.total / 1024 / 1024 / 1024:.2f} GB")
    print(f"Used: {disk_info.used / 1024 / 1024 / 1024:.2f} GB")
    print(f"Free: {disk_info.free / 1024 / 1024 / 1024:.2f} GB")
except FileNotFoundError:
    print("Disk info not available on this system")

Here’s my output:

Total: 460.43 GB
Used: 8.23 GB
Free: 214.41 GB

Note that free disk + used disk may not equal to total disk because some disk space may be reserved for special purposes or not reported by the system, such as:

  • In Linux, by default, 5% of the disk space is reserved for the root user and not available for regular users. This is done to prevent the system from running out of space and crashing.
  • On Mac systems, especially with the APFS (Apple File System) file system, the disk space may be shared by multiple volumes or snapshots that are not counted separately. This is because APFS uses a container scheme that allows different volumes to share the same space and only allocate it when needed.
Advertisements

Determining the amount of resources being used will help you with many things, such as adding logic to prevent server overload, etc. Happy coding & have a nice day!

반응형