Certainly! Below is a Python script named usage.py that reports CPU, GPU, and memory usage accurately. It utilizes the following libraries:
psutil for CPU and memory usage.
pynvml for detailed GPU usage (NVIDIA GPUs).
tabulate for nicely formatted output in the terminal.
Prerequisites:
Before running the script, ensure you have the required packages installed:
pip install psutil pynvml tabulate
Here's the usage.py script:
# usage.py
import psutil
from tabulate import tabulate
try:
import pynvml # NVIDIA Management Library for GPU stats
pynvml.nvmlInit()
NVML_AVAILABLE = True
except ImportError:
NVML_AVAILABLE = False
pynvml = None
def get_cpu_usage():
"""Get CPU usage statistics."""
cpu_usage = psutil.cpu_percent(interval=1)
cpu_freq = psutil.cpu_freq()
cpu_cores = psutil.cpu_count(logical=False)
cpu_threads = psutil.cpu_count()
cpu_stats = psutil.cpu_stats()
return {
'Usage (%)': cpu_usage,
'Frequency (MHz)': cpu_freq.current if cpu_freq else 'N/A',
'Cores': cpu_cores,
'Threads': cpu_threads,
'Context Switches': cpu_stats.ctx_switches,
'Interrupts': cpu_stats.interrupts,
'Soft Interrupts': cpu_stats.soft_interrupts,
'Syscalls': cpu_stats.syscalls
}
def get_memory_usage():
"""Get memory usage statistics."""
mem = psutil.virtual_memory()
swap = psutil.swap_memory()
return {
'Total (GB)': f"{mem.total / (1024 ** 3):.2f}",
'Available (GB)': f"{mem.available / (1024 ** 3):.2f}",
'Used (GB)': f"{mem.used / (1024 ** 3):.2f}",
'Usage (%)': mem.percent,
'Swap Total (GB)': f"{swap.total / (1024 ** 3):.2f}",
'Swap Used (GB)': f"{swap.used / (1024 ** 3):.2f}",
'Swap Usage (%)': swap.percent
}
def get_gpu_usage():
"""Get GPU usage statistics using NVIDIA's pynvml."""
if not NVML_AVAILABLE:
return "pynvml module not installed or NVIDIA drivers not found."
device_count = pynvml.nvmlDeviceGetCount()
gpu_list = []
for i in range(device_count):
handle = pynvml.nvmlDeviceGetHandleByIndex(i)
mem_info = pynvml.nvmlDeviceGetMemoryInfo(handle)
utilization = pynvml.nvmlDeviceGetUtilizationRates(handle)
temp = pynvml.nvmlDeviceGetTemperature(handle, pynvml.NVML_TEMPERATURE_GPU)
power_draw = pynvml.nvmlDeviceGetPowerUsage(handle) / 1000 # Convert to Watts
power_limit = pynvml.nvmlDeviceGetEnforcedPowerLimit(handle) / 1000 # Convert to Watts
fan_speed = pynvml.nvmlDeviceGetFanSpeed(handle)
name = pynvml.nvmlDeviceGetName(handle)
serial = pynvml.nvmlDeviceGetSerial(handle)
pci_info = pynvml.nvmlDeviceGetPciInfo(handle)
gpu_list.append({
'ID': i,
'Name': name.decode('utf-8'),
'Serial': serial.decode('utf-8'),
'PCI Bus': f"{pci_info.bus:02x}",
'PCI Device': f"{pci_info.device:02x}",
'GPU Usage (%)': utilization.gpu,
'Memory Usage (%)': utilization.memory,
'Memory Used (MB)': f"{mem_info.used / (1024 ** 2):.2f}",
'Memory Total (MB)': f"{mem_info.total / (1024 ** 2):.2f}",
'Temperature (°C)': temp,
'Power Draw (W)': f"{power_draw:.2f}",
'Power Limit (W)': f"{power_limit:.2f}",
'Fan Speed (%)': fan_speed
})
pynvml.nvmlShutdown()
return gpu_list
def main():
cpu_info = get_cpu_usage()
print("\n=== CPU Info ===")
print(tabulate([cpu_info], headers="keys", tablefmt="grid"))
mem_info = get_memory_usage()
print("\n=== Memory Info ===")
print(tabulate([mem_info], headers="keys", tablefmt="grid"))
print("\n=== GPU Info ===")
gpu_info = get_gpu_usage()
if gpu_info and isinstance(gpu_info, list):
print(tabulate(gpu_info, headers="keys", tablefmt="grid"))
else:
print(gpu_info)
if __name__ == "__main__":
main()
Explanation:
-
CPU Usage:
- The script uses
psutil.cpu_percent() to get the CPU usage percentage.
- It also retrieves CPU frequency, core and thread count, and CPU stats like context switches and interrupts.
-
Memory Usage:
- Uses
psutil.virtual_memory() to get RAM statistics.
- Includes total, available, used memory, and memory usage percentage.
- Also includes swap memory statistics.
-
GPU Usage:
- Uses
pynvml to interact with NVIDIA GPUs.
- Retrieves per-GPU statistics such as memory usage, GPU utilization, temperature, power draw, fan speed, and more.
- Handles cases where
pynvml is not installed or NVIDIA drivers are not present.
-
Output Formatting:
- Uses the
tabulate library to display information in a readable table format.
Running the Script:
To execute the script, open your terminal and run:
python usage.py
Sample Output:
=== CPU Info ===
+------------------+------------------+---------+-----------+-----------------+-------------+-----------------+-----------+
| Usage (%) | Frequency (MHz) | Cores | Threads | Context Switches | Interrupts | Soft Interrupts | Syscalls |
+==================+==================+=========+===========+=================+=============+=================+===========+
| 12.5 | 2592.001 | 4 | 8 | 12345 | 6789 | 3456 | 7890 |
+------------------+------------------+---------+-----------+-----------------+-------------+-----------------+-----------+
=== Memory Info ===
+-------------+---------------+--------------+------------+-----------------+----------------+----------------+
| Total (GB) | Available (GB)| Used (GB) | Usage (%) | Swap Total (GB) | Swap Used (GB) | Swap Usage (%) |
+=============+===============+==============+============+=================+================+================+
| 15.92 | 7.85 | 8.07 | 50.7 | 2.00 | 0.25 | 12.5 |
+-------------+---------------+--------------+------------+-----------------+----------------+----------------+
=== GPU Info ===
+------+----------------+----------+-----------+-------------+----------------+------------------+-------------------+-------------------+-----------------+-----------------+----------------+---------------+
| ID | Name | Serial | PCI Bus | PCI Device | GPU Usage (%) | Memory Usage (%) | Memory Used (MB) | Memory Total (MB) | Temperature (°C) | Power Draw (W) | Power Limit (W) | Fan Speed (%) |
+======+================+==========+===========+=============+================+==================+===================+===================+=================+=================+================+===============+
| 0 | NVIDIA GeForce | 12345678 | 01 | 00 | 20 | 10 | 1024 | 4096 | 55 | 75.0 | 150.0 | 30 |
+------+----------------+----------+-----------+-------------+----------------+------------------+-------------------+-------------------+-----------------+-----------------+----------------+---------------+
Notes:
- The actual output will vary based on your system's hardware and current resource utilization.
- If you have multiple GPUs, the script will display information for each one.
- If
pynvml cannot find NVIDIA drivers or GPUs, it will display a message indicating so.
Troubleshooting:
- If you receive an error about
pynvml not being found, ensure NVIDIA drivers are installed and accessible.
- For non-NVIDIA GPUs, you may need to use other libraries or methods to gather GPU statistics.
- Ensure all required Python packages are installed with the correct versions.
Feel free to customize the script further to suit your specific needs!