Python : Efficient CPU usage monitoring with Psutil

python @ Freshers.in

Monitoring CPU usage is essential in performance analysis, system optimization, and ensuring efficient resource management in any computing environment. Monitoring CPU usage in Python is straightforward with the psutil library. Whether you are developing a resource-intensive application, managing a server, or just curious about your system’s performance, this Python-based approach offers a flexible and efficient solution.

Why monitor CPU usage?

  • Performance optimization: Understanding CPU utilization helps in optimizing applications for better performance.
  • Resource management: It aids in efficient allocation and utilization of computing resources.
  • Troubleshooting: Identifying high CPU usage can help in diagnosing and resolving system bottlenecks.

Tools required

  • Python: Ensure you have Python installed on your system.
  • psutil Library: A cross-platform library for retrieving information on system utilization (CPU, memory, disks, network, sensors) in Python.

Installing psutil

First, install the psutil library using pip:

pip install psutil

Writing a Python script to monitor CPU usage

Below is a simple Python script that uses psutil to monitor and print the CPU usage percentage.

Step 1: Import psutil
import psutil
Step 2: Define a Function to Get CPU Usage
def get_cpu_usage():
    # Retrieve and return the CPU usage percentage
    return psutil.cpu_percent(interval=1)

The cpu_percent method provides the system-wide CPU utilization as a percentage. The interval parameter specifies the number of seconds to wait before retrieving the usage. A longer interval provides a more averaged percentage.

Step 3: Main loop to monitor CPU usage continuously
import time
while True:
    cpu_usage = get_cpu_usage()
    print(f"Current CPU Usage: {cpu_usage}%")
    time.sleep(5)  # Sleep for 5 seconds before checking again

This loop continuously checks the CPU usage every 5 seconds and prints the current CPU usage percentage.

Advanced monitoring

For more advanced monitoring, you can:

  • Track usage over tme: Store the CPU usage data in a file or database for historical analysis.
  • Monitor per-core usage: Use psutil.cpu_percent(interval=1, percpu=True) to get usage for each core.
  • Integrate with visualization tools: Use libraries like Matplotlib to visualize CPU usage over time.

Refer more on python here :

Author: user