TOP中CPU状态信息含义

在linux中,我们通过top命令可以监控所有进程的运行情况。包括进程号,进程目前状态,CPU使用,以及mem占用等。


同时在top界面按 1 可以进入到所有CPU统计界面。(按 2 与 3 可以查看不同node节点中CPU的使用情况)


进入后可以发现每个CPU都有8个相应描述信息(us,sy,ni,id,wa,hi,si,st)。这里我们摘出官方解释:

us:user cpu time (or) % CPU time spent in user space

sy:system cpu time (or) % CPU time spent in kernel space

ni :user nice cpu time (or) % CPU time spent on low priority processes

id :idle cpu time (or) % CPU time spent idle

wa :io wait cpu time (or) % CPU time spent in wait (on disk)

hi :hardware irq (or) % CPU time spent servicing/handling hardware interrupts

si :software irq (or) % CPU time spent servicing/handling software interrupts

st :steal time - - % CPU time in involuntary wait by virtual cpu while hypervisor is servicing another processor (or) % CPU time stolen from a virtual machine

### 关于 `top` 命令中 `%CPU` 字段的含义和计算方式 #### 1. `%CPU` 字段的定义 在 Linux 系统中,`top` 命令中的 `%CPU` 字段表示一个固定时间间隔内,某个进程所消耗的 CPU 时间占总 CPU 时间的比例[^2]。这个比例反映了该进程在这段时间内的活跃程度。 对于单核处理器而言,如果某进程完全占据了这颗核心,则其 `%CPU` 可能达到 100%;而对于多核系统来说,当进程利用了多个核心时,`%CPU` 的数值可能会超过 100%,具体取决于它实际占用的核心数量以及这些核心上的负载情况[^4]。 #### 2. `%CPU` 的计算方法 为了理解如何得出这一数据,我们需要深入到操作系统的实现层面: - **基础概念** - 内核维护了一组称为 per-CPU 统计的数据结构 (如 kernel_cpustat),它们位于 `_per_cpu_start` 到 `__per_cpu_end` 这一地址范围内[^3]。 - **统计过程** - 当调用 `top` 或其他监控工具读取当前状态时,程序会查询上述统计数据并对比前后两次采样之间的差异。 - **公式表达** 假设 T 是采样的时间段长度(单位秒),U 表示这段时间里特定进程中运行态的时间片总数(也叫 jiffies,在不同的硬件架构下有不同的分辨率)。那么可以按照如下方式进行估算: \[ \%CPU = \left(\frac{U}{T} \times S\right) / N \] 其中, - \( U \): 用户空间加系统空间累计耗时; - \( T \): 实际经过的真实世界钟表时间; - \( S \): 单位转换因子(通常等于 100); - \( N \): 如果目标机器有多颗逻辑处理单元的话就是物理或者虚拟 cpu 数量。 因此,最终呈现出来的百分比不仅考虑到了单一任务本身的执行效率,同时也综合考量了整个平台环境下的并发特性][^[^24]。 ```python def calculate_cpu_usage(user_time, system_time, elapsed_realtime, num_cpus=1): total_process_time = user_time + system_time percentage = (total_process_time / elapsed_realtime * 100) / num_cpus return round(percentage, 2) # Example usage of the function with hypothetical values. example_user_time = 50 # Hypothetical value representing user mode time spent by a process during sampling period. example_system_time = 30 # Same as above but for syscalls/kernel operations performed on behalf of that same process. example_elapsed_realtime = 80 # Time passed between two consecutive measurements. calculated_percentage = calculate_cpu_usage(example_user_time, example_system_time, example_elapsed_realtime) print(f"The calculated %CPU is {calculated_percentage}%.") ``` 以上代码片段展示了一个简化版的方法用于模拟基于已知参数的手动计算流程。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值