CPU and RAM Usage Monitor
This utility monitors system resource usage in real-time. It uses psutil to fetch CPU percentage and memory statistics, displaying them in a continuously updating log format.
Modules Used:
psutil: To retrieve system utilization statistics.time: To handle timestamps and intervals.
Installation
pip install psutil
The Code
Save this as monitor.py.
import psutil
import time
def monitor_resources(interval=1):
print(f"Monitoring System Resources (Interval: {interval}s)")
print("Press Ctrl+C to stop.")
print("-" * 55)
# Header
print(f"{'Time':<10} {'CPU (%)':<10} {'Memory (%)':<12} {'Memory (GB)':<10}")
print("-" * 55)
try:
while True:
# cpu_percent with interval blocks for that duration
# This calculates the average CPU usage over the interval
cpu = psutil.cpu_percent(interval=interval)
memory = psutil.virtual_memory()
mem_percent = memory.percent
mem_used = memory.used / (1024 ** 3) # Convert Bytes to GB
timestamp = time.strftime("%H:%M:%S")
print(f"{timestamp:<10} {cpu:<10.1f} {mem_percent:<12.1f} {mem_used:<10.2f}")
except KeyboardInterrupt:
print("\nMonitoring stopped.")
if __name__ == "__main__":
# You can adjust the interval (in seconds) here
monitor_resources(interval=1)
Usage
python monitor.py
The script will run indefinitely, printing a new line of stats every second, until you interrupt it with Ctrl+C.