DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Trending

  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  • Customer 360: Fraud Detection in Fintech With PySpark and ML
  • Designing a Java Connector for Software Integrations
  • Mastering Advanced Aggregations in Spark SQL

Using Psutil Module for System Monitoring [+Bonus]

In this post, we'll learn to use the Python Psutil module for system monitoring and how can we visualize reports with the Python data visualization tool called Plotly.

By 
Veronika Vasileva user avatar
Veronika Vasileva
·
Jan. 17, 22 · Tutorial
Likes (10)
Comment
Save
Tweet
Share
4.9K Views

Join the DZone community and get the full member experience.

Join For Free

Let’s face it: the mighty Task Manager isn’t a magic wand for all operations. Thus, managing system processes and profiling is better off without it. Unless you’re into the dread of manual and repetitive checks. That is why we need an effective alternative to assess the impact of our test.

With this in mind, you might need to create a script that goes through the system processes and provides a report when the script runs.

This is where the Psutil module comes into the limelight. It provides valuable functions that help deal with system processes and ease the strain. 

A Few Lines About Psutil

If you’re reading this post, you must know the ins and outs of this module. But just in case, let me brush up on your knowledge while we’re here. Psutil is the Python module that is suitable for system monitoring, profiling as well as limiting the resources of the processes and managing the running processes.

Put simply, Psutil is a third-party module that obtains information about information. The Psutil module can be used on different platforms and supports Linux / UNIX / OSX / Windows etc. You can install it by simply typing pip install Psutil in the cmd command line

How To Use Psutil: A Short Guide

Here’s how we can leverage this Python library.

First, let’s import libraries:

Then, we’ll create an empty dataframe:

Script Snapshot - 2

The function psutil.cpu_percent() provides the current system-wide CPU utilization in the form of a percentage. It requires a time interval as a parameter (e.g. seconds). Make sure you include a time interval because CPU use is calculated over a period of time.

Script Snapshot - 3

The next function is psutil.disk usage (path). It returns a tuple of disk usage statistics for a given path. The total, used, and free space, as well as the % consumption, are all stated in bytes.Script Snapshot - 4

Going over to the next function, psutil.virtual_memory () provides insight into the system memory usage. It returns the value of total RAM capacity in bytes. This value remains constant, but we’ll need it later for graph plotting.

Script Snapshot - 5 

Let's convert to gigabytes:

Script Snapshot - 6

and round up to two digits:

Script Snapshot - 7

Then, we’ll return the amount of used RAM at the moment of a startup, in bytes. Let's convert it to gigabytes and round up to two digits:

Script Snapshot - 8

You can add any metrics to the report in case it is your matter of concern and monitoring. Feel free to check out more about metrics in Psutil's documentation. 

Let's add another percentage of used RAM.

Script Snapshot - 9

Then, we’ll set a variable to the current date and add all values to the dataframe relevant for the current time. 

After that, we’ll write the new value into a CSV file.

Script Snapshot - 10


Your final script will look like this:

Script Snapshot - 11

However, you wouldn’t like activating it manually every five minutes. So I suggest you set up a scheduler that takes care of your script automatically.

By running it every 2/3/5 or 10 minutes, we will gather statistics about our system load. Reports like these are useful to get a fuller image of the system under load, and whether you can reduce downtime and add some extra load. In large organizations, such reports will help the executives get a look into the capacity in use and budget planning for resource expansion. 

On that note, let’s see how we can visualize reports in this context. Here’s our bonus section.

Creating Charts and Graphs With Python Plotly

Plotly is one of the richest Python data visualization tools for Data Science.

Although the Pandas, Matplotlib, and Seaborn libraries are excellent libraries for plotting data, they are fit for statistical graphs. In most cases, statistical plots are enough to channel the message. 

However, in some cases, you may want to spruce up your reports by making them more interactive. Besides, Plotly allows you to create a whole lot of visualizations, including line plots, area and bar charts, box plots, heatmaps, and others.

So here’s how we can use Plotly for visualizing your data.

First, let’s import the Plotly graphic libraries that we’ll need for plotting. Then we’ll write a file path (the one that collects information about system processes).
Script Snapshot - 12

Let's start plotting the graph.

First set the bar on which we are going to plot.Script Snapshot - 13

 Add a new trace using add_trace() method

Then we’ll write the chart title in the name.

On the X-axis, let’s plot the time and along the Y-axis, start with a value that will be used as a total virtual memory value. We know that this is a constant and we want to see a straight line on the graph. To highlight our resource limits,  we’ll make it red in the line_color parameter.Script Snapshot - 14

Let's draw our graph, but since it's big, let’s take it to the HTML page. 

Don’t worry: the interactive functionality will be fine. 

Script Snapshot - 15

The first graph is down. Let's add two more indicators - CPU load and memory usage.

Since CPU load is expressed in percentage and uses a different measurement system than RAM, let’s make it pale blue. This way, it won’t divert our focus, yet we’ll be able to observe the correlation of index fluctuations with the running processes.

Script Snapshot - 16

Note that the interactivity of plotly allows you to show or hide traces by clicking or double-clicking on the legend. 

Second Python Plotly Graph

You can also use time scale zoom to see the day/hour and zoom back to see the year.

Let's add buttons to the chart for a more convenient data view. We’ll do it:

- per day

- per week

- per month

- per year

Script Snapshot - 17

Third Python Plotly Graph

Fourth Python Plotly Graph

Fifth Python Plotly Graph

Et voila! Just like that, you have created your chart with Plotly.

Opinions expressed by DZone contributors are their own.

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!