导语
哈喽!大家好,我是木木子!准时上线给大家更新啦!
Ps:小故事
前两天有位粉丝朋友在群里问我说,有没有不装一些我们熟知的电脑管理软件但是依然可以查看CPU的使用率方法,或者能够介绍一款比较给力的小插件也好。确实,在生活中有不少人是不喜欢装那些管理软件的。
今天,木木子就给大家介绍一款手写编程代码的小脚本,能够轻松在界面上展示:利用Python实时监控CPU使用率,随时展现。也无需下载管理软件,几十行代码即可搞定~
一、模块简介
1.0 关于模块的详细用法参考
1.1 用到psutil模块
小介绍:
psutil是一个跨平台库(code.google.com/p/psutil/)
括CPU、内存、磁盘、网络等)信息。它主要应用于系统监控,分析和限制系统资源及进程的管理。
它实现了同等命令行工具提供的功能,如ps、top、lsof、netstat、ifconfig、who、df、kill、free、nice、ionice、
iostat、iotop、uptime、pidof、tty、taskset、pmap等。
目前支持32位和64位的Linux、Windows、OS X、FreeBSD和Sun Solaris等操作系统。
1.2 用到matplotlib模块
小介绍:
Matplotlib 是一个 Python 的 2D绘图库,它以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形。
通过 Matplotlib,开发者可以仅需要几行代码,便可以生成绘图,直方图,功率谱,条形图,错误图,散点图等。
二、准备中
2.1 相关环境
**Python3.6、Pycharm。****相关模块:**matplotlib模块;psutil模块。
2.2 安装
这里小编统一使用:pip install -i pypi.douban.com/simple/+模块名
三、开始敲代码
3.1 代码内容
利用Python实时监控CPU使用率:
- 执行用户进程
- 执行内核进程和中断
- CPU处于空闲状态
主要是这三个方面的代码编写过程。
3.2 附完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
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_autoscale_on( False ) ax.set_xticks([]) ax.set_yticks( range ( 0 , 101 , 10 )) ax.grid( True ) # 执行用户进程的时间百分比 user = [ None ] * POINT # 执行内核进程和中断的时间百分比 sys = [ None ] * POINT # CPU处于空闲状态的时间百分比 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 ]] l_user.set_ydata(user) l_sys.set_ydata(sys) l_idle.set_ydata(idle) while True : try : ax.draw_artist(l_user) ax.draw_artist(l_sys) ax.draw_artist(l_idle) break except : pass ax.figure.canvas.draw() def start_monitor(): timer = fig.canvas.new_timer(interval = 100 ) timer.add_callback(OnTimer, ax) timer.start() plt.show() if __name__ = = '__main__' : start_monitor() |
四、效果展示
静态截图展示——
到此这篇关于基于Python实现实时监控CPU使用率的文章就介绍到这了,更多相关Python监控CPU内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://juejin.cn/post/7087883749148327949