Linux平台Cpu使用率的计算

Linux平台Cpu使用率的计算

proc文件系统

/proc文件系统是一个伪文件系统,它只存在内存当中,而不占用外存空间。它以文件系统的方式为内核与进程提供通信的接口。用户和应用程序可以通过/proc得到系统的信息,并可以改变内核的某些参数。由于系统的信息,如进程,是动态改变的,所以用户或应用程序读取/proc目录中的文件时,proc文件系统是动态从系统内核读出所需信息并提交的。

/proc目录中有一些以数字命名的目录,它们是进程目录。系统中当前运行的每一个进程在/proc下都对应一个以进程号为目录名的目录/proc/pid,它们是读取进程信息的接口。此外,Linux 2.6.0-test6以上的版本中/proc/pid目录中有一个task目录,/proc/pid/task目录中也有一些以该进程所拥有的线程的线程号命名的目录/proc/pid/task/tid,它们是读取线程信息的接口。

/proc/cpuinfo文件

         该文件中存放了有关 cpu的相关信息(型号,缓存大小等)。

[zhengangen@buick ~]$ cat /proc/cpuinfo

processor       : 0

vendor_id       : GenuineIntel

cpu family      : 15

model           : 4

model name      : Intel(R) Xeon(TM) CPU 3.00GHz

stepping        : 10

cpu MHz         : 3001.177

cache size      : 2048 KB

physical id     : 0

siblings        : 2

core id         : 0

cpu cores       : 1

fdiv_bug        : no

hlt_bug         : no

f00f_bug        : no

coma_bug        : no

fpu             : yes

fpu_exception   : yes

cpuid level     : 5

wp              : yes

flags           : fpu vme de pse tsc msr pae mce cx8 apic mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe lm pni monitor ds_cpl cid xtpr

bogomips        : 6004.52

 

说明:以下只解释对我们计算Cpu使用率有用的相关参数。

         参数                            解释

processor (0)                       cpu的一个物理标识

 

结论1:可以通过该文件根据processor出现的次数统计cpu的逻辑个数(包括多核、超线程)

/proc/stat文件

         该文件包含了所有CPU活动的信息,该文件中的所有值都是从系统启动开始累计到当前时刻。不同内核版本中该文件的格式可能不大一致,以下通过实例来说明数据该文件中各字段的含义。

实例数据:2.6.24-24版本上的

 

fjzag@fjzag-desktop:~$ cat /proc/stat

cpu  38082 627 27594 893908 12256 581 895 0 0

cpu0 22880 472 16855 430287 10617 576 661 0 0

cpu1 15202 154 10739 463620 1639 4 234 0 0

intr 120053 222 2686 0 1 1 0 5 0 3 0 0 0 47302 0 0 34194 29775 0 5019 845 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

ctxt 1434984

btime 1252028243

processes 8113

procs_running 1

procs_blocked 0

第一行的数值表示的是CPU总的使用情况,所以我们只要用第一行的数字计算就可以了。下表解析第一行各数值的含义:

参数          解析(单位:jiffies)

(jiffies是内核中的一个全局变量,用来记录自系统启动一来产生的节拍数,在linux中,一个节拍大致可理解为操作系统进程调度的最小时间片,不同linux内核可能值有不同,通常在1ms到10ms之间)

user (38082)   从系统启动开始累计到当前时刻,处于用户态的运行时间,不包含 nice值为负进程。

nice (627)     从系统启动开始累计到当前时刻,nice值为负的进程所占用的CPU时间

system (27594从系统启动开始累计到当前时刻,处于核心态的运行时间

idle (893908)  从系统启动开始累计到当前时刻,除IO等待时间以外的其它等待时间iowait (12256)从系统启动开始累计到当前时刻,IO等待时间(since 2.5.41)

irq (581)          从系统启动开始累计到当前时刻,硬中断时间(since 2.6.0-test4)

softirq (895    从系统启动开始累计到当前时刻,软中断时间(since 2.6.0-test4)stealstolen(0)                  which is the time spent in other operating systems when running in a virtualized environment(since 2.6.11)

guest(0)                              which is the time spent running a virtual  CPU  for  guest operating systems under the control of the Linux kernel(since 2.6.24)

 

结论2:总的cpu时间totalCpuTime = user + nice + system + idle + iowait + irq + softirq + stealstolen  +  guest

/proc/<pid>/stat文件                                          

该文件包含了某一进程所有的活动的信息,该文件中的所有值都是从系统启动开始累计

到当前时刻。以下通过实例数据来说明该文件中各字段的含义。

 

[zhengangen@buick ~]# cat /proc/6873/stat

6873 (a.out) R 6723 6873 6723 34819 6873 8388608 77 0 0 041958 31 0 0 25 0 3 0 5882654 1409024 56 4294967295 134512640 134513720 3215579040 0 2097798 0 0 0 0 0 0 0 17 0 0 0

 

说明:以下只解释对我们计算Cpu使用率有用相关参数

参数                                                                解释

pid=6873                            进程号

utime=1587                       该任务在用户态运行的时间,单位为jiffies

stime=41958                      该任务在核心态运行的时间,单位为jiffies

cutime=0                            所有已死线程在用户态运行的时间,单位为jiffies

cstime=0                            所有已死在核心态运行的时间,单位为jiffies

 

结论3进程的总Cpu时间processCpuTime = utime + stime + cutime + cstime,该值包括其所有线程的cpu时间。

/proc/<pid>/task/<tid>/stat文件

该文件包含了某一进程所有的活动的信息,该文件中的所有值都是从系统启动开始累计到当前时刻。该文件的内容格式以及各字段的含义同/proc/<pid>/stat文件。

         注意,该文件中的tid字段表示的不再是进程号,而是linux中的轻量级进程(lwp),即我们通常所说的线程。

 

结论4:线程Cpu时间threadCpuTime = utime + stime

系统中有关进程cpu使用率的常用命令

ps 命令

通过ps命令可以查看系统中相关进程的Cpu使用率的信息。以下在linux man文档中对ps命令输出中有关cpu使用率的解释:

 

CPU usage is currently expressed as the percentage of time spent running during the entire lifetime of a process. This is not ideal, and it does not conform to the standards that ps otherwise conforms to. CPU usage is unlikely to add up to exactly 100%.

 

%cpu   cpu utilization of the process in "##.#" format. It is the CPU time used                           divided by the time the process has been running (cputime/realtime ratio),                           expressed as a percentage. It will not add up to 100% unless you are lucky.

 

结论5ps命令算出来的cpu使用率相对于进程启动时的平均值,随着进程运行时间的增大,该值会趋向于平缓。

top命令

通过top命令可以查看系统中相关进程的实时信息(cpu使用率等)。以下是man文档中对top命令输出中有关进程cpu使用率的解释。

 

#C  --  Last used CPU (SMP)                   A number representing the last used processor. In a true  SMP  environment  this  will  likely change  frequently  since  the  kernel intentionally uses weak affinity.  Also, the very act of running top may break this weak affinity and cause more processes to  change  CPUs  more  often (because of the extra demand for cpu time).

 

%CPU  --  CPU usage                   The  task’s share of the elapsed CPU time since the last screen update, expressed as a percent-age of total CPU time. In a true SMP environment, if  Irix mode is Off, top will operate in Solaris mode where a task’s cpu usage will be divided by the total number of CPUs.

 

结论6某一个线程在其运行期间其所使用的cpu可能会发生变化。

结论7在多核的情况下top命令输出的cpu使用率实质是按cpu个数*100%计算的。<!--[if !supportAnnotations]-->

单核情况下Cpu使用率的计算

基本思想

通过读取/proc/stat 、/proc/<pid>/stat、/proc/<pid>/task/<tid>/stat以及/proc/cpuinfo这几个文件获取总的Cpu时间、进程的Cpu时间、线程的Cpu时间以及Cpu的个数的信息,然后通过一定的算法进行计算(采样两个足够短的时间间隔的Cpu快照与进程快照来计算进程的Cpu使用率)。

 

总的Cpu使用率计算

计算方法:

<!--[if !supportLists]-->1、  <!--[endif]-->采样两个足够短的时间间隔的Cpu快照,分别记作t1,t2,其中t1、t2的结构均为:

(user、nice、system、idle、iowait、irq、softirq、stealstolen、guest)的9元组;

<!--[if !supportLists]-->2、  <!--[endif]-->计算总的Cpu时间片totalCpuTime

<!--[if !supportLists]-->a)         <!--[endif]-->把第一次的所有cpu使用情况求和,得到s1;

<!--[if !supportLists]-->b)         <!--[endif]-->把第二次的所有cpu使用情况求和,得到s2;

<!--[if !supportLists]-->c)         <!--[endif]-->s2 - s1得到这个时间间隔内的所有时间片,即totalCpuTime = j2 - j1 ;

3、计算空闲时间idle

idle对应第四列的数据,用第二次的第四列 - 第一次的第四列即可

idle=第二次的第四列 - 第一次的第四列

6、计算cpu使用率

pcpu =100* (total-idle)/total

某一进程Cpu使用率的计算

计算方法:  

<!--[if !supportLists]-->1.               <!--[endif]-->采样两个足够短的时间间隔的cpu快照与进程快照,

<!--[if !supportLists]-->a)         <!--[endif]-->每一个cpu快照均为(user、nice、system、idle、iowait、irq、softirq、stealstolen、guest)的9元组;

<!--[if !supportLists]-->b)         <!--[endif]-->每一个进程快照均为 (utimestimecutimecstime)4元组;

<!--[if !supportLists]-->2.               <!--[endif]-->分别根据结论2、结论3计算出两个时刻的总的cpu时间与进程的cpu时间,分别记作:totalCpuTime1totalCpuTime2processCpuTime1processCpuTime2

<!--[if !supportLists]-->3.               <!--[endif]-->计算该进程的cpu使用率pcpu = 100*( processCpuTime2 – processCpuTime1) / (totalCpuTime2 – totalCpuTime1) (按100%计算,如果是多核情况下还需乘以cpu的个数);

实验数据

实验一: 监控一空循环的进程的cpu使用率。

说明:左边的数据是按以上算法得到的数据,其中采样的时间间隔与top命令刷新屏幕的时间间隔相同。

按以上方法计算得到的cpu使用率

通过top命令得到的

 

99.50083

98.333336

98.0

98.83138

99.0

99.0

99.83361

98.83527

98.4975

 

PID    USER      PR   NI   VIRT   RES   SHR   S  %CPU %MEM  TIME+  COMMAND 

7639 fjzag     20   0  206m  10m 7136 S   99  2.2   1:00.74 java              

 7639 fjzag     20   0  206m  10m 7136 S   99  2.2   1:03.71 java              

 7639 fjzag     20   0  206m  10m 7136 S   99  2.2   1:06.67 java              

 7639 fjzag     20   0  206m  10m 7136 S   99  2.2   1:09.63 java              

 7639 fjzag     20   0  206m  10m 7136 S   98  2.2   1:12.59 java              

 7639 fjzag     20   0  206m  10m 7136 S   99  2.2   1:15.55 java              

 7639 fjzag     20   0  206m  10m 7136 S  100  2.2   1:18.55 java              

 7639 fjzag     20   0  206m  10m 7136 S  100  2.2   1:21.54 java              

 7639 fjzag     20   0  206m  10m 7136 S   99  2.2   1:24.52 java              

 7639 fjzag     20   0  206m  10m 7136 S   98  2.2   1:27.46 java

 

实验二: 监控jconsole进程的cpu使用率。

说明:左边的数据是按以上算法得到的数据,其中采样的时间间隔与top命令刷新屏幕的时间间隔相同。

按以上方法计算得到的cpu使用率

通过top命令得到的

 

8.681135

12.0

10.350584

7.6539097

7.6539097

5.0

13.021703

11.0

8.666667

PID   USER      PR   NI  VIRT   RES   SHR  S  %CPU %MEM  TIME+  COMMAND 

7753 fjzag     20   0  252m  72m  22m S   10 14.4   0:18.70 jconsole          

 7753 fjzag     20   0  252m  72m  22m S   12 14.4   0:19.07 jconsole          

 7753 fjzag     20   0  252m  72m  22m S   11 14.4   0:19.39 jconsole          

 7753 fjzag     20   0  252m  72m  22m S    7 14.4   0:19.61 jconsole          

 7753 fjzag     20   0  252m  72m  22m S    7 14.4   0:19.83 jconsole          

 7753 fjzag     20   0  252m  72m  22m S    5 14.4   0:19.97 jconsole          

 7753 fjzag     20   0  252m  72m  22m S   14 14.4   0:20.38 jconsole          

 7753 fjzag     20   0  252m  72m  22m S   10 14.4   0:20.68 jconsole          

 7753 fjzag     20   0  252m  72m  22m S    9 14.5   0:20.96 jconsole

某一线程Cpu使用率的计算

计算方法:  

<!--[if !supportLists]-->1.               <!--[endif]-->采样两个足够短的时间隔的cpu快照与线程快照,

<!--[if !supportLists]-->a)         <!--[endif]-->每一个cpu快照均为(user、nice、system、idle、iowait、irq、softirq、stealstealon、guest)的9元组;

<!--[if !supportLists]-->b)         <!--[endif]-->每一个线程快照均为 (utimestime)2元组;

<!--[if !supportLists]-->2.               <!--[endif]-->分别根据结论2、结论4计算出两个时刻的总的cpu时间与线程的cpu时间,分别记作:totalCpuTime1totalCpuTime2threadCpuTime1threadCpuTime2

<!--[if !supportLists]-->3.               <!--[endif]-->计算该线程的cpu使用率pcpu = 100*( threadCpuTime2 – threadCpuTime1) / (totalCpuTime2 – totalCpuTime1) (按100%计算,如果是多核情况下还需乘以cpu的个数);

实验数据

实验一: 监控一空循环的线程的cpu使用率。

说明:左边的数据是按以上算法得到的数据,其中采样的时间间隔与top命令刷新屏幕的时间间隔相同。

按以上方法计算得到的cpu使用率

通过top命令得到的

 

98.83138

97.00997

96.98997

97.49583

98.169716

96.8386

97.333336

93.82304

98.66667

PID    USER      PR   NI   VIRT   RES   SHR   S  %CPU %MEM  TIME+  COMMAND 

7649 fjzag     20   0  206m  10m 7136 R   97  2.2   7:22.94 java              

 7649 fjzag     20   0  206m  10m 7136 R   97  2.2   7:25.86 java              

 7649 fjzag     20   0  206m  10m 7136 R   97  2.2   7:28.76 java              

 7649 fjzag     20   0  206m  10m 7136 R   99  2.2   7:31.72 java              

 7649 fjzag     20   0  206m  10m 7136 R   98  2.2   7:34.65 java              

 7649 fjzag     20   0  206m  10m 7136 R   96  2.2   7:37.53 java              

 7649 fjzag     20   0  206m  10m 7136 R   98  2.2   7:40.47 java              

 7649 fjzag     20   0  206m  10m 7136 R   96  2.2   7:43.34 java              

 7649 fjzag     20   0  206m  10m 7136 R   97  2.2   7:46.25 java

 

实验二: 监控jconsole程序某一线程的cpu使用率。

说明:左边的数据是按以上算法得到的数据,其中采样的时间间隔与top命令刷新屏幕的时间间隔相同。

按以上方法计算得到的cpu使用率

通过top命令得到的

 

1.3400335

6.644518

1.3333334

0.6677796

0.6666667

1.3333334

1.3333334

 PID    USER      PR   NI   VIRT   RES  SHR  S  %CPU %MEM  TIME+  COMMAND 

7755 fjzag     20   0  251m  72m  22m S    1 14.4   0:11.92 jconsole          

 7755 fjzag     20   0  251m  72m  22m S    7 14.4   0:12.12 jconsole          

 7755 fjzag     20   0  251m  72m  22m S    2 14.4   0:12.18 jconsole          

 7755 fjzag     20   0  251m  72m  22m S    0 14.4   0:12.18 jconsole          

 7755 fjzag     20   0  251m  72m  22m S    1 14.4   0:12.20 jconsole          

 7755 fjzag     20   0  251m  72m  22m S    1 14.4   0:12.24 jconsole          

 7755 fjzag     20   0  251m  72m  22m S    1 14.4   0:12.28 jconsole

多核情况下cpu使用率的计算                                                    

以下通过实验数据来说明多核情况下某一进程cpu使用率是按cpu个数*100%计算的.

实验一
描述:

双核的情况下作的一组实验,第一组数据是通过ps -eLo pid,lwp,pcpu | grep 9140命令查看进程号为9140的进程中各线程的详细信息。第二组数据是通过 ps命令查看进程号为9140进程的cpu使用率。

数据一:

pid  lwp  %cpu

9140  9140  0.0
 9140  9141  0.0
 9140  9142  0.0
 9140  9143  0.0
 9140  9144  0.0
 9140  9149  0.0
 9140  9150  0.0
 9140  9151  0.0
 9140  9152  0.1
 
9140  9153 96.6                        该线程是一个空循环
 9140  9154 95.9
                         该线程是一个空循环

以上除了红色标注出来的两个线程以外,其他的线程都是后台线程。

数据二:

pid  %cpu

9140  193

实验二
描述:

单核的情况下作的一组实验,第一组数据是通过ps -eLo pid,lwp,pcpu | grep 6137命令查看进程号为6137的进程中各线程的详细信息。第二组数据是通过 ps命令查看进程号为6137进程的cpu使用率。

数据一:

 pid    lwp   %cpu

 6137  6137  0.0

 6137  6138  0.1

 6137  6143  0.0

 6137  6144  0.0

 6137  6145  0.0

 6137  6146  0.0

 6137  6147  0.0

 6137  6148  0.0

 6137  6149  0.0

 6137  6150 46.9                                                空循环线程

 6137  6151 46.9                                                空循环线程

以上除了红色标注出来的两个线程以外,其他的线程都是后台线程。

数据二

pid %cpu

6137 92.9

主要问题:

<!--[if !supportLists]-->1.       <!--[endif]-->不同内核版本/proc/stat文件格式不大一致。/proc/stat文件中第一行为总的cpu使用情况。

各个版本都有的4个字段: user、nice、system、idle

2.5.41版本新增字段:iowait

2.6.0-test4新增字段:irq、softirq

2.6.11新增字段:stealstolen :                    which is the time spent in other operating

systems when running in a virtualized environment

2.6.24新增字段:guest:                                    which is the time spent running a virtual  CPU  for  guest operating systems under the control of the Linux kernel

2./proc/pid/task目录是Linux 2.6.0-test6之后才有的功能。

 

3.关于出现cpu使用率为负的情况,目前想到的解决方案是如果出现负值,连续采样计算cpu使用率直到为非负。

 

4. 有些线程生命周期较短,可能在我们采样期间就已经死掉了.

 

转载自http://www.blogjava.net/fjzag/articles/317773.html 

 

实例代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>   //头文件
struct occupy        //声明一个occupy的结构体
{
        char name[20];      //定义一个char类型的数组名name有20个元素
        unsigned int user;  //定义一个无符号的int类型的user
        unsigned int nice;  //定义一个无符号的int类型的nice
        unsigned int system;//定义一个无符号的int类型的system
        unsigned int idle;  //定义一个无符号的int类型的idle
};
float g_cpu_used;           //定义一个全局的float类型g_cpu_used
int cpu_num;                //定义一个全局的int类型cup_num
void cal_occupy(struct occupy *, struct occupy *);  //声明无类型的函数cal_occupy包含两个结构体参数
void get_occupy(struct occupy *);                   //声明无类型的函数get_occupy包含一个结构体参数
int main()                  //主函数开始
{
  struct occupy ocpu[10];   //定义occupy结构体变量名是ocpu含10个元素
  struct occupy ncpu[10];   //定义occupy结构体变量名是ncpu含10个元素
  int i;                    //定义一个局部int变量i
 
  cpu_num = sysconf(_SC_NPROCESSORS_ONLN);   //系统调用返回cpu的个数赋给cpu_num
  for(;;)                                    //死循环
  { 
      sleep(1);                               //等待1秒
      get_occupy(ocpu);                       //调用get函数带回结构体数组第一次
      sleep(1);                               //等待1秒
      get_occupy(ncpu);                       //调用get函数带回结构体数组第二次
      for (i=0; i<cpu_num; i++)               //循环cpu_num-1次
      {
              cal_occupy(&ocpu[i], &ncpu[i]); //调用cal函数带回结构体数组
              printf("%f \n", g_cpu_used);    //打印g_cpu_used的使用情况以6位小数显示
      }
  }
}
void
cal_occupy (struct occupy *o, struct occupy *n)//对无类型cal函数含有两个形参结构体类型的指针变量O和N
{
    double od, nd;   //定义双精度实型变量od,nd
    double id, sd;   //定义双精度实型变量id,sd
    double scale;    //定义双精度实型变量scale
    od = (double) (o->user + o->nice + o->system +o->idle);//第一次(用户+优先级+系统+空闲)的时间再赋给od
    nd = (double) (n->user + n->nice + n->system +n->idle);//第二次(用户+优先级+系统+空闲)的时间再赋给od
    scale = 100.0 / (float)(nd-od);       //100除强制转换(nd-od)之差为float类型再赋给scale这个变量
    id = (double) (n->user - o->user);    //用户第一次和第二次的时间之差再赋给id
    sd = (double) (n->system - o->system);//系统第一次和第二次的时间之差再赋给sd
    g_cpu_used = ((sd+id)*100.0)/(nd-od); //((用户+系统)乖100)除(第一次和第二次的时间差)再赋给g_cpu_used
}
void
get_occupy (struct occupy *o) //对无类型get函数含有一个形参结构体类弄的指针O
{
    FILE *fd;         //定义文件指针fd
    int n;            //定义局部变量n为int类型
    char buff[1024];  //定义局部变量buff数组为char类型大小为1024
                                                                                                             
    fd = fopen ("/proc/stat", "r"); //以R读的方式打开stat文件再赋给指针fd
    fgets (buff, sizeof(buff), fd); //从fd文件中读取长度为buff的字符串再存到起始地址为buff这个空间里
    for(n=0;n<cpu_num;n++)          //循环cpu_num-1次
    {
      fgets (buff, sizeof(buff),fd);//从fd文件中读取长度为buff的字符串再存到起始地址为buff这个空间里
      /*下面是将buff的字符串根据参数format后转换为数据的结果存入相应的结构体参数 */
      sscanf (buff, "%s %u %u %u %u", &o[n].name, &o[n].user, &o[n].nice,&o[n].system, &o[n].idle);
      /*下面是错误的输出 */
      fprintf (stderr, "%s %u %u %u %u\n", o[n].name, o[n].user, o[n].nice,o[n].system, o[n].idle);
    }
   fclose(fd);     //关闭文件fd
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值