[Python is awesome] a powerful professional tool for real-time monitoring CPU utilization is fresh~


Hello! Hello, I'm kimiko! On time to update you!

Ps: little story 🌲

Two days ago, a fan friend asked me in the group whether we can still check it without installing some well-known computer management software

CPU usage rate, or can introduce a relatively small plug-in awesome. Indeed, many people don't like it in life

Install those management software.

Today, mumuzi will introduce you a small script of handwritten programming code, which can be easily displayed on the interface: using Python to implement

Monitor CPU usage when.

It can be displayed at any time without downloading the management software. Dozens of lines of code can be done~

The complete material + source code of all articles are in 👇👇

Fans white whoring source code benefits, please move to CSDN community



Module introduction 🌴

🌳 1.0 detailed usage reference of module

psutil file: https://psutil.readthedocs.io/en/latest/
matplotlib file: https://matplotlib.org/users/index.html

🌳 1.1 using psutil module

Brief introduction:

Psutil is a cross platform library( http://code.google.com/p/psutil/ ), it can easily obtain the process and information of system operation

System utilization (including CPU, memory, disk, network, etc.) information. It is mainly used in system monitoring, analyzing and limiting system resources

Source and process management.

It implements the functions provided by the same command-line tools, such as ps, top, lsof, netstat, ifconfig, who, df, kill, free

nice, ionice, iostat, iotop, uptime, pidof, tty, taskset, pmap, etc.

At present, it supports 32-bit and 64 bit operating systems such as Linux, Windows, OS X, FreeBSD and Sun Solaris.

🌳 1.2 use matplotlib module

Brief introduction:

Matplotlib is a Python 2D graphics library, which generates publishing quality in a variety of hard copy formats and cross platform interactive environments

Rank graphical . Through Matplotlib, developers can generate graphs, histograms and power spectra with just a few lines of code,

Bar chart, error chart, scatter chart, etc.

2, In preparation 🌴

🌳 2.1 relevant environment

Python3.6,Pycharm. Related modules: matplotlib module; psutil module.

🌳 2.2 installation

Here, the small series are used uniformly: pip install -i https://pypi.douban.com/simple / + module name

3, Start typing code 🌴

🌳 3.1 code content

Monitor CPU usage in real time with Python:

  • Execute user process
  • Execute kernel processes and interrupts
  • CPU is idle

It is mainly the coding process of these three aspects.

🌳 3.2 complete code attached

import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
import psutil as p

POINTS = 300
fig, ax = plt.subplots()
ax.set_ylim([0, 100])
ax.set_xlim([0, POINTS])
ax.set_yticks(range(0, 101, 10))
# Percentage of time spent executing user processes
user = [None] * POINT
# Percentage of time spent executing kernel processes and interrupts
sys = [None] * POINT
# Percentage of time the CPU is idle
idle = [None] * POINT
l_user, = ax.plot(range(POINTS), user, label='User %')
l_sys, = ax.plot(range(POINTS), sys, label='Sys %')
l_idle, = ax.plot(range(POINTS), idle, label='Idle %')
ax.legend(loc='upper center', ncol=4, prop=font_manager.FontProperties(size=10))
bg = fig.canvas.copy_from_bbox(ax.bbox)

def cpu_usage():
	t = p.cpu_times()
	return [t.user, t.system, t.idle]

before = cpu_usage()

def get_cpu_usage():
	global before
	now = cpu_usage()
	delta = [now[i] - before[i] for i in range(len(now))]
	total = sum(delta)
	before = now
	return [(100.0*dt)/(total+0.1) for dt in delta]

def OnTimer(ax):
	global user, sys, idle, bg
	tmp = get_cpu_usage()
	user = user[1:] + [tmp[0]]
	sys = sys[1:] + [tmp[1]]
	idle = idle[1:] + [tmp[2]]
	while True:

def start_monitor():
	timer = fig.canvas.new_timer(interval=100)
	timer.add_callback(OnTimer, ax)

if __name__ == '__main__':

4, Effect display 🌴

🌳 4.1 dynamic video display——

Use Python to monitor CPU utilization in real time!

🌳 4.2 static screenshot display——


Hee hee, the article ends here. After fans get the code, they feel that this gadget is still very practical and has a little partner of love

You can ask me for the source code and eat it at ease~

🎯 Complete free source code collection: find me! You can get it yourself at the end of the article, and so can didi!

🎉 Some previous articles recommended——

Item 1.3 video player

After using the agreed Python exclusive ad free video player, I have a conscience to call crazy for it

Item 3.2 automatic wallpaper change

[Python advanced skills] it's super cool. The computer automatically changes the wallpaper every day. This artifact is suitable for you.

Item 3.3 # WordArt signature

[WordArt signature generator]] the parents' signature on the test paper was rejected | "I think I can save it again. Do you think so“

Item 3.9 # code to live in the snowy scenery and snow flying applet

[Python code to live in snow scenery applet] the strongest introduction of snow scenery portrait: let you be 10 times beautiful and drunk (Chinese people don't cheat Chinese people)

Project 4.0 # GIF making magic (Douluo continent as an example)

[Python artifact] this fool GIF making tool is recommended. Don't say it again in the future (easy to use ~)

🎄 Article summary——

Item 1.0 Python-2021 | summary of existing articles | continuously updated. It's enough to read this article directly

(more content + source code are summarized in the article!! welcome to read ~)

Tags: Python cpu

Posted by expl0it on Mon, 18 Apr 2022 22:06:23 +0930