Windows下,大家可以使用任务理器来查看系统的各种资源使用情况,我们常常比较关心的就是CPU使用率,在Linux,同样有这样可视化的软件,但是大家可能会好奇那些不断变化的数字是怎样计算出来的?
下面,我就来分析一下psutil是怎样计算CPU的使用率的。
简单介绍一下psutil,psutil是一个python获取当前系统资源的第三方模块,可以跨平台的获取系统的各方面资源。
psutil获取系统cpu使用率的方法是cpu_percent(),其有两个参数,分别是interval和percpu,interval指定的是计算cpu使用率的时间间隔,percpu则指定是选择总的使用率还是每个cpu的使用率
描述系统cpu使用情况主要有一下几点:

user          从系统启动到现在,CPU处于用户态的运行时间。不包含nice值为负的进程。
nice          从系统启动到现在,CPUnice为负值的进程占用的cpu时间
system        从系统启动到现在,CPU处于内核态的运行时间
idle          从系统启动到现在,CPU除了 iowait外的等待时间
iowait        从系统启动到现在,CPUio 等待时间
irq           从系统启动到现在,CPU硬中断花费的时间
softirq       从系统启动到现在,CPU软中断花费的时间
steal         从系统启动到现在,CPU运行其他虚拟环境中的操作系统花费的时间
guest         从系统启动到现在,CPU运行在通过Linux内核控制的客户操作系统上的虚拟cpu的时间
guest_nice    从系统启动到现在,CPU运行在通过Linux内核控制的客户操作系统上的虚拟cpu的时间, nice 为负值进程

知道了以上参数的意思,计算某段时间内的cpu使用率就不难,由于cpu资源是在高速的变化,于是计算cpu使用率只能是在一段时间内的,设置两个时间点为t1和t2,
CPU在t1和t2时间内总的使用时间:( user2+ nice2+ system2+ idle2+ iowait2+ irq2+ softirq2 + steal2 + guest2 + guest_nice2 ) - ( user1+ nice1+ system1+ idle1+ iowait1+ irq1+ softirq1 + steal1 + guest1 + guest_nice1)
CPU的空闲时间:(idle2 -idle1)
CPU在t1和t2时间内的使用率=CPU非空闲时间/CPU总时间*100%=(1-CPU的空闲时间/CPU总时间)*100%
则:
    CPU(t1,t2)使用率:1-(idle2-idle1)/(( user2+ nice2+ system2+ idle2+ iowait2+ irq2+ softirq2 + steal2 + guest2 + guest_nice2 ) - ( user1+ nice1+ system1+ idle1+ iowait1+ irq1+ softirq1 + steal1 + guest1 + guest_nice1))

简单了解了使用率的计算方法,下面我们看一下cpu_percent是怎样实现的

def cpu_percent(interval=None, percpu=False):"""Return a float representing the current system-wide utilization as a percentage.返回一个当前系统cpu使用率的百分比结果,When interval is > 0.0 compares system CPU times elapsed beforeand after the interval (blocking).当interval大于0.0时,返回的是在这段时间内CUP的使用率When interval is 0.0 or None compares system CPU times elapsedsince last call or module import, returning immediately (nonblocking). That means the first time this is called it willreturn a meaningless 0.0 value which you should ignore.In this case is recommended for accuracy that this function becalled with at least 0.1 seconds between calls.当interval是0.0或者是None时,系统在调用此模块后,还没来得及运行就立即返回了,返回的是没有任何意义的0,你应该忽略调这个值,为避免这种情况,为了准确,调用这个模块时间至少为0.1秒When percpu is True returns a list of floats representing theutilization as a percentage for each CPU.First element of the list refers to first CPU, second elementto second CPU and so on.The order of the list is consistent across calls.当percpu的值为True时,则返回的是一个列表,里面包含每个CPU在该段时间内的CPU使用率Examples:>>> # blocking, system-wide>>> psutil.cpu_percent(interval=1)2.0>>>>>> # blocking, per-cpu>>> psutil.cpu_percent(interval=1, percpu=True)[2.0, 1.0]>>>>>> # non-blocking (percentage since last call)>>> psutil.cpu_percent(interval=None)2.9>>>"""global _last_cpu_times  #全局变量,用于表示上一个时间点cpu的各项参数,用于和下一个时间点cpu各项参数进行计算global _last_per_cpu_times #全局变量,用于表示上一个时间点,各个cpu在上一个时间点的各项cpu参数,作用同上blocking = interval is not None and interval > 0.0 #判断interval的值,如果interval 不为空且大余0.0,则blocking值为真,否则为假def calculate(t1, t2):  #计算CPU使用率t1_all = sum(t1) #计算t1时间,cpu的使用时间,为各项参数的和t1_busy = t1_all - t1.idle #计算cpu的非空闲时间t2_all = sum(t2) #计算t1时间,cpu的使用时间,为各项参数的和t2_busy = t2_all - t2.idle #计算cpu的非空闲时间# this usually indicates a float precision issueif t2_busy <= t1_busy:  #如果t2时刻的非空闲时间小余t1时刻的,则直接返回0.0return 0.0busy_delta = t2_busy - t1_busy  #计算t1-t2时间段内CPU总的非空闲时间all_delta = t2_all - t1_all     #计算t1-t2时间段内CPU总的使用时间busy_perc = (busy_delta / all_delta) * 100  #计算t1-t2时间段内CPU总的使用率return round(busy_perc, 1) #保留一位小数后返回# system-wide usageif not percpu:   #如果percpu为Falseif blocking: #interval 不为空且大余0.0t1 = cpu_times() #获取t1时刻,cpu各项参数time.sleep(interval) #休眠interval时间else:t1 = _last_cpu_times #如果不满足interval 不为空且大余0.0if t1 is None:  #当interval为None# Something bad happened at import time. We'll# get a meaningful result on the next call. See:# https://github.com/giampaolo/psutil/pull/715t1 = cpu_times()#当interval为None,_last_cpu_times与t1几乎是在同一时刻计算的,值几乎相同,因此将返回0.0_last_cpu_times = cpu_times()return calculate(t1, _last_cpu_times)# per-cpu usageelse:ret = []if blocking:tot1 = cpu_times(percpu=True)time.sleep(interval)else:tot1 = _last_per_cpu_timesif tot1 is None:# Something bad happened at import time. We'll# get a meaningful result on the next call. See:# https://github.com/giampaolo/psutil/pull/715tot1 = cpu_times(percpu=True)_last_per_cpu_times = cpu_times(percpu=True)for t1, t2 in zip(tot1, _last_per_cpu_times):ret.append(calculate(t1, t2)) #循环计算各个CPU的使用率return ret# Use separate global vars for cpu_times_percent() so that it's
# independent from cpu_percent() and they can both be used within
# the same program.
_last_cpu_times_2 = _last_cpu_times
_last_per_cpu_times_2 = _last_per_cpu_times

CPU使用率的计算方法相关推荐

  1. Prometheus 查询语言 PromQL 的 CPU 使用率计算方法

    CPU 使用率的计算方法 翻了几篇 Prometheus 的 PromQL 查询 cpu 使用率的文章,说得都不是特别透,结合一篇英文文章终于搞明白了怎么计算这个指标. cpu 模式 一颗 cpu 要 ...

  2. 单片机里面的CPU使用率是什么鬼?

    打开电脑的任务管理器,看着跳动的CPU使用率,发现很舒服.每一个线程占用了多少CPU清清楚楚,也就能针对性的确认为啥你的电脑跑的慢了. 今天这篇笔记不讲每个任务(或线程)CPU的使用情况,而是单片机整 ...

  3. cpu使用率_漫话性能:CPU使用率

    序言 CPU 使用率是最直观和最常用的系统性能指标,更是我们在排查性能问题时,通常会关注的第一个指标. 节拍率 为了维护 CPU 时间,Linux 通过事先定义的节拍率(内核中表示为 HZ),触发时间 ...

  4. cpu使用率_单片机里面的CPU使用率是什么鬼?

    打开电脑的任务管理器,看着跳动的CPU使用率,发现很舒服.每一个线程占用了多少CPU清清楚楚,也就能针对性的确认为啥你的电脑跑的慢了. 今天这篇笔记不讲每个任务(或线程)CPU的使用情况,而是单片机整 ...

  5. linux查看cpu的赫兹,linux平台jiffies和HZ Cpu使用率

    HZ:1秒钟内,时钟中断的次数,即1秒钟内,系统时钟的节拍次数. jiffies:全局变量,用来记录系统自启动以来产生的节拍总数 系统运行时间(以秒为单位):system_time=(jiffies) ...

  6. 关于cpu 使用率【转】

    来源:Linux中通过/proc/stat等文件计算Cpu使用率 - - BlogJava 总的Cpu使用率计算 计算方法: 1.  采样两个足够短的时间间隔的Cpu快照,分别记作t1,t2,其中t1 ...

  7. 某个应用的CPU使用率达到100%,如何排查

    CPU使用率是单位时间内CPU的使用情况的统计,以百分比的方式展现.那么,作为最常见也是最熟悉的CPU指标,CPU的使用率是如何算出来的?再有诸如top.ps之类的性能工具展示的%user.%nice ...

  8. 查看cpu使用率。查看进程占用cpu百分比

     /proc/ /stat 包含了所有CPU活跃的信息,该文件中的所有值都是从系统启动开始累计到当前时刻. [root@localhost ~]# cat /proc/6873/stat 6873 ( ...

  9. 【linux性能优化】CPU使用率过高分析

    最常用什么指标来描述系统的 CPU 性能呢? 可能不是平均负载,也不是 CPU上下文切换,而是另一个更直观的指标CPU使用率 CPU使用率是单位时间内CPU使用情况的统计,以百分比的方式展示 那么,作 ...

最新文章

  1. 强化学习入门教程(附学习大纲)
  2. block为什么用copy以及如何解决循环引用
  3. access 打印预览 代码_标签打印软件如何批量打印样品标签
  4. SAP CRM WebClient UI 某些icon图标不能正常显示X
  5. Nginx负载均衡策略有哪些?知识点总结+面试题解析
  6. RabbitMQ初识
  7. 获取iOS任意线程调用堆栈(四)符号化实战
  8. java/01/java简介,java基本概念,java基本类型的划分
  9. 简单说说JAVA的String和byte[]的关系
  10. C 标准库 —— scanf(fflush(stdin))
  11. 单机 搭建kafka集群 本地_单机简单搭建一个kafka集群(没有进行内核参数和JVM的调优)...
  12. 【问题解决】VS Code官网下载速度慢的解决办法
  13. amtemu.v0.9.2-painter.exe百度网盘下载
  14. UI设计中常见的各种布局有哪些?|优漫动游
  15. Pycharm菜单栏消失,(File 、view消失)快速调出来的方法。(Professional Edition 2022版)
  16. 基于802.1q技术实现单线复用的一种思路
  17. Matlab 基础04 - 冒号Colon operator “:”的使用和复杂应用详析
  18. “今日头条”发展困境与未来发展策略
  19. 到底什么是区块链?数字货币技术开发朔源
  20. eb8000软件怎样上传_EB8000程序上传与下载

热门文章

  1. html 选择第二个元素,css选择器,选中第二个p,实现第三个和第四个p的效果,
  2. 带有serpstack的实时Google搜索结果API
  3. seurat使用笔记(数据处理、PCA、聚类)
  4. python logger handler_Python中的logger和handler到底是个什么鬼
  5. crout分解计算例题_如何计算有理函数的不定积分
  6. 电脑硬件升级——笔记本更换更大容量的固态硬盘,并进行系统迁移
  7. 统信UOS系统添加Windows系统共享的打印机
  8. Chrome源码剖析、上--多线程模型、进程通信、进程模型
  9. 第12周前端学习周报
  10. 【深度学习】图像分割概述