Hello everyone, in this tutorial we will develop a program that will monitor the use of the computer's CPU and memory.
But before we get started, let's define some terms so we understand exactly what we're going to do.
What is monitoring?
To monitor means continuously monitoring and observing a situation, a process or a system in search of changes or anomalies. It is an essential activity in several fields, such as information technology, medicine, engineering, security, among others.
In the context of information Technology, monitoring usually involves keeping track of a computer system's performance, such as CPU, memory, storage, and network usage, as well as the status of running services and applications. This makes it possible to identify possible problems or bottlenecks that could affect the quality and availability of the service or system.
Monitoring can also involve collecting data, analyzing and viewing real-time or historical metrics to identify trends and patterns of behavior that may indicate problems or opportunities for improvement. This data can be used to make informed decisions and implement corrective or preventive actions.
What is a CPU?
The CPU (Central Processing Unit), also known as the processor, is the main component of a computer responsible for executing instructions and processing data. It is responsible for fetching the instructions stored in memory, executing them and storing the results.
The CPU is made up of several components, including the Control Unit (UC), which is responsible for controlling the flow of data within the CPU, and the Arithmetic Logic Unit (ALU), which is responsible for performing mathematical and logical operations. needed to execute the instructions.
CPU speed is measured in Hertz (Hz) and indicates the number of clock cycles the CPU is capable of executing per second. The higher the clock frequency, the faster the CPU can execute instructions and process data.
The CPU is a fundamental component for the operation of a computer and its performance has a significant impact on the overall performance of the system. Some of the major CPU manufacturers include Intel, AMD, Qualcomm and ARM.
What is Memory?
Memory is a fundamental component of a computer that temporarily stores data so that it can be accessed quickly by the processor. It is responsible for storing data and programs that are currently running, as well as data and programs that have recently been used and may be accessed again soon.
There are several types of memory in a computer, including RAM (Random Access Memory), which is the main random access memory in the system and is used to store the data and programs that are currently in use. Cache memory is another form of high-speed memory used to temporarily store the data most used by the processor, while virtual memory is a form of auxiliary memory used by the operating system to simulate more memory than the physical memory available in the system.
The amount of memory available on a system can have a significant impact on overall system performance, especially when running resource intensive applications. It is important to choose the right amount of memory to meet the needs of the system and the applications that will run on it.
What is monitoring CPU and memory usage?
Monitoring a system's CPU and memory usage means keeping track of how many resources the processor and memory are being used at any given time. The processor (CPU) is the main component of the computer responsible for executing instructions and processing data. Memory is responsible for temporarily storing data so that it can be accessed quickly by the processor.
Monitoring CPU and memory usage is useful for a variety of purposes, such as identifying potential system performance bottlenecks, diagnosing software or hardware issues, optimizing resource allocation in cloud computing environments, and assessing the impact of changes to software or system hardware.
There are several tools and libraries that allow you to monitor CPU and memory usage on operating systems such as Windows, macOS and Linux. The library psutil in Python is one such tool that allows you to monitor system resource usage.
Python psutil library
The psutil library is an open source Python library that provides an easy-to-use interface for monitoring and interacting with operating system processes, system resource usage information such as CPU, memory, disk, and network usage, and other system information. system.
In this tutorial, we'll explore the features of the psutil library and how to use them in your own Python projects.
Installation
Before you start using the psutil library, you need to install it. This can easily be done using the pip package manager. Open a terminal and run the following command:
pip install psutilWith the library installed, let's now explore its features.
Get System Information in Python
The first thing we can do with the psutil library is get system information like CPU, memory and disk information. Let's start with CPU information.
import psutil
# get CPU usage info
cpu_percent = psutil.cpu_percent()
print(f"cpu usage: {cpu_percent}%")The methodcpu_percent() returns the percentage of current CPU usage. It is important to note that this percentage can be greater than 100% if the system has more than one processor or processing core.
Now, let's get memory usage information:
# get memory usage information
memory = psutil.virtual_memory()
print(f"Memory usage: {memory.percent}%")
The method virtual_memory() returns an object namedtuple which contains information about memory usage such as current usage, available usage, swap usage, and more. In this example, we are just printing the percentage of memory usage.
We can also get disk usage information:
# get disk usage information
disk_usage = psutil.disk_usage("/")
print(f"disk usage: {disk_usage.percent}%")The method disk_usage() returns an object namedtuple which contains information about disk usage, such as total space, used space, and free space. In this example, we are just printing the percentage of disk usage on the root of the filesystem.
Get process information in Python
In addition to getting system information, the psutil library also allows you to get detailed information about processes running on the system. Let's get a list of all running processes:
# get list of processes
processes = psutil.process_iter()
for process in processes:
print(f"PID: {process.pid}, Name: {process.name()}")
The method process_iter() returns an iterator that can be used to iterate over all processes running on the system. For each process, we are printing its ID and its name.
We can also obtain detailed information about a specific process using its process ID (PID):
# get information from a specific process
process = psutil.Process(1) # PID 1 is the init process on Linux
print(f"Name: {process.name()}, Status: {process.status()}")
The method Process() create an object Process for a specific process, based on its process ID.
Real-time monitoring of CPU and system memory usage in Python
To monitor a system's CPU and memory usage in Python with a live bar graph, we can use the psutil library to get information about the system, and the matplotlib library to generate the graph in real time.
We will develop the code explaining line by line, so we will have the following.
import psutil
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimationThe libraries psuti the matplotlib are imported, as well as the class FuncAnimation from the library matplotlib.animation.
# Configure the plot
fig, ax = plt.subplots()
ax.set_ylim(0, 100)
ax.set_xlim(0, 100)
ax.set_title('CPU and Memory Usage')
ax.set_xlabel('Time')
ax.set_ylabel('Usage (%)')
cpu_line, = ax.plot([], [], label='CPU', color='#FF5733')
mem_line, = ax.plot([], [], label='Memory', color='#C70039')
ax.legend()The chart is configured and some of its properties are set, such as its title and axis labels. Two lines are created to represent CPU and memory usage respectively. The object ax.legend() creates a legend for the chart data.
# Add text to the CPU and Memory values
cpu_text = ax.text(0.77, 0.7, '', transform=ax.transAxes)
mem_text = ax.text(0.77, 0.6, '', transform=ax.transAxes)Two text objects are created to display current CPU and memory usage values.
# Update function for the plot
def update_chart(frame):
# Get CPU usage information
cpu_percent = psutil.cpu_percent()
# Get memory usage information
memory = psutil.virtual_memory()
memory_percent = memory.percent
# Add data to the plot
cpu_line.set_data(list(range(frame)), [cpu_percent]*frame)
mem_line.set_data(list(range(frame)), [memory_percent]*frame)
# Update the text with CPU and Memory values
cpu_text.set_text(f'CPU: {cpu_percent:.1f}%')
mem_text.set_text(f'Memory: {memory_percent:.1f}%')
return cpu_line, mem_line, cpu_text, mem_text
This function update_chart is responsible for updating the graph with the new CPU and memory usage values on each frame of the animation. The function calls the function psutilto get the CPU and memory usage information, then it updates the information on the two lines of the graph. The frame value frame is passed to the function so that the graph can display the history of CPU and memory usage. The function then updates the display texts of the current CPU and memory usage values.
# Animate the plot
animation = FuncAnimation(fig, update_chart, frames=100, interval=1000, blit=True)The function FuncAnimation is used to animate the graph. It calls the function update_chart at regular time intervals specified in milliseconds. In this case, the graph is updated every second (1000 milliseconds), for a total of 100 frames.
# Style the plot lines
for line in [cpu_line, mem_line]:
line.set_linewidth(2)
line.set_marker('o')
line.set_markersize(5)
# Set the background color of the plot
ax.set_facecolor('#F5F5F5')
# Show the plot
plt.show()Now the code enters a section where some styling is performed on the graphic before finally displaying it on the screen.
the code snippet for line in [cpu_line, mem_line]: is responsible for applying styles to chart lines. Here, a loop is used to loop through the two graph lines, CPU and Memory.
For each line, the following style changes are made:
- line.set_linewidth(2): Sets the line thickness to 2 points.
- line.set_marker('o'): Sets the marker to a circle.
- line.set_markersize(5): Sets the marker size to 5 points.
After that, the background of the chart is styled using the methodax.set_facecolor('#F5F5F5'). It sets the chart's background color to a light gray.
Lastly, the method plt.show() is called to display the graph on the screen.
Full Code
Note that the purpose of the code is to monitor the CPU and memory usage of the system and show the data in a graph in real time, allowing the user to follow changes in the use of these resources over time.
Using the psutil library allows you to obtain CPU and memory usage information, which are stored in the cpu_percent and memory_percent variables, respectively.
This information is then used to update the two lines on the graph representing CPU and memory usage respectively. The set_data() function is used to update row data with new values.
Furthermore, the function set_text() is used to update the texts displayed on the graph with the updated CPU and memory values.
Finally, some stylizations are made to the chart, such as changing the line thickness and the size of the markers, as well as defining the background color of the chart. The command plt.show() is used to display the graph on the screen.
In short, this code is a simple implementation of a real-time CPU and memory usage monitor using the library psutil and the matplotlib plotting library. It is useful for analyzing system behavior regarding the use of these resources.
import psutil
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# Configure the plot
fig, ax = plt.subplots()
ax.set_ylim(0, 100)
ax.set_xlim(0, 100)
ax.set_title('CPU and Memory Usage')
ax.set_xlabel('Time')
ax.set_ylabel('Usage (%)')
cpu_line, = ax.plot([], [], label='CPU', color='#FF5733')
mem_line, = ax.plot([], [], label='Memory', color='#C70039')
ax.legend()
# Add text to the CPU and Memory values
cpu_text = ax.text(0.77, 0.7, '', transform=ax.transAxes)
mem_text = ax.text(0.77, 0.6, '', transform=ax.transAxes)
# Update function for the plot
def update_chart(frame):
# Get CPU usage information
cpu_percent = psutil.cpu_percent()
# Get memory usage information
memory = psutil.virtual_memory()
memory_percent = memory.percent
# Add data to the plot
cpu_line.set_data(list(range(frame)), [cpu_percent]*frame)
mem_line.set_data(list(range(frame)), [memory_percent]*frame)
# Update the text with CPU and Memory values
cpu_text.set_text(f'CPU: {cpu_percent:.1f}%')
mem_text.set_text(f'Memory: {memory_percent:.1f}%')
return cpu_line, mem_line, cpu_text, mem_text
# Animate the plot
animation = FuncAnimation(fig, update_chart, frames=100, interval=1000, blit=True)
# Style the plot lines
for line in [cpu_line, mem_line]:
line.set_linewidth(2)
line.set_marker('o')
line.set_markersize(5)
# Set the background color of the plot
ax.set_facecolor('#F5F5F5')
# Show the plot
plt.show()
0 Comments