linux下的内存CPU等资源的使用情况可通过解析虚拟文件系统/proc的相关文件获得。htop就是通过解析该目录下的/proc/stat文件得到CPU的核数以及动态的使用情况。
可通过cat /proc/stat命令查看该文件内容,下面是该文件中的第一行,以及每个量对应的意义:
cpu 148627 236 41339 2372383 38801 0 1500 0 0 0
name user nice system idle iowait irq softirq steal guest
The 8th column is called steal_time. It counts the ticks spent
executing other virtual hosts (in virtualised environments like Xen)
Note2:
With Linux 2.6.24 there is 9th column for (virtual) guest systems.
(引自: http://www.linuxhowtos.org/System/procstat.htm)
htop中CPU使用率计算方式
定义总的忙时间allbasytime=user+nice+system+irq+softirq
定义总的运行时间allruntime=allbasytime+idle+iowait+steal+guest
在两个时间相近的时间点t0和t1读取/proc/stat文件,计算出allbasytime_t0, allruntime_t0, allbasytime_t1, allruntime_t1
在某段时间内CPU的使用率计算公式为:
userate=(allbasytime_t1 – allbasytime_t0) / (allruntime_t1 – allruntime_t1) * 100.0
根据这个原理,可以通过如下得到CPU的使用率:
可通过cat /proc/stat命令查看该文件内容,下面是该文件中的第一行,以及每个量对应的意义:
cpu 148627 236 41339 2372383 38801 0 1500 0 0 0
name user nice system idle iowait irq softirq steal guest
- user: normal processes executing in user mode
- nice: niced processes executing in user mode
- system: processes executing in kernel mode
- idle: twiddling thumbs
- iowait: waiting for I/O to complete
- irq: servicing interrupts
- softirq: servicing softirqs
The 8th column is called steal_time. It counts the ticks spent
executing other virtual hosts (in virtualised environments like Xen)
Note2:
With Linux 2.6.24 there is 9th column for (virtual) guest systems.
(引自: http://www.linuxhowtos.org/System/procstat.htm)
htop中CPU使用率计算方式
定义总的忙时间allbasytime=user+nice+system+irq+softirq
定义总的运行时间allruntime=allbasytime+idle+iowait+steal+guest
在两个时间相近的时间点t0和t1读取/proc/stat文件,计算出allbasytime_t0, allruntime_t0, allbasytime_t1, allruntime_t1
在某段时间内CPU的使用率计算公式为:
userate=(allbasytime_t1 – allbasytime_t0) / (allruntime_t1 – allruntime_t1) * 100.0
根据这个原理,可以通过如下得到CPU的使用率:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct{
char name[20];
unsigned long long user;
unsigned long long nice;
unsigned long long system;
unsigned long long idle;
unsigned long l