让多核CPU占用率曲线听你指挥(Linux实现)——《编程之美》1.1继续学习

来源:互联网 发布:超级优化女主角有谁 编辑:程序博客网 时间:2024/05/22 14:24

让多核CPU占用率曲线听你指挥(Linux实现)——《编程之美》1.1继续学习

分类:计算机系统4477人阅读 评论(2)收藏举报
linux编程structtimezonenullpython

本回将尝试在Linux环境下能否在系统监视器中画出一个正弦曲线。本人环境为Ubuntu 11.04.

基本思想还是和Windows下面的相同,更换系统调用,便可以实现功能的迁移。

[cpp] view plaincopyprint?
  1. #include <time.h>  
  2. #include <sys/time.h>  
  3. #include <unistd.h>  
  4. #include<stdlib.h>  
  5. #include<math.h>  
  6.   
  7. #define DWORD unsigned long  
  8. #define UINT64 unsigned long long  
  9. const double SPLIT = 0.01;  
  10. const int COUNT = 200;  
  11. const double PI = 3.14159265;  
  12. const int INTERVAL = 300;  
  13.   
  14. int main(int argc, char* argv[] )  
  15. {  
  16.     struct timeval tms;  
  17.     DWORD busySpan[COUNT];  
  18.     DWORD idleSpan[COUNT];  
  19.     int half = INTERVAL/2, i;  
  20.     double radian = 0.0;  
  21.     for(i = 0; i < COUNT; ++i)  
  22.     {  
  23.         busySpan[i] = (DWORD)(half + (sin(PI * radian) * half));  
  24.         idleSpan[i] = INTERVAL - busySpan[i];  
  25.         radian += SPLIT;  
  26.     }  
  27.     clock_t startTime = 0;  
  28.     int j = 0;  
  29.     while(1)  
  30.     {  
  31.         j = j % COUNT;  
  32.         timerclear(&tms);  
  33.         gettimeofday(&tms,NULL);  
  34.         UINT64 startTime = tms.tv_usec;  
  35.         while(1)//clock返回该进程从启动到现在经历的毫秒数(千分之一秒)  
  36.         {  
  37.             timerclear(&tms);  
  38.             gettimeofday(&tms,NULL);  
  39.             UINT64 nowTime = tms.tv_usec;  
  40.             if((nowTime - startTime)/1000 > busySpan[j])  
  41.                 break;  
  42.         }  
  43.             if(usleep(idleSpan[j]*1000))  //精确到微秒(百万分之一秒)的函数  
  44.                 exit(-1);  
  45.         j++;  
  46.     }  
  47.     return 0;  
  48. }  


gettimeofday()函数用来取得当前时间(微秒,百万分之一秒)。并通过参数传递给结构体timeval类型的tms。

int gettimeofday(struct timeval *tv, struct timezone *tz);

tz用来获取时区信息。不做介绍。

结构体timeval的定义为:

struct timeval

{

         time_t                tv_sec;            //seconds

         suseconds_t    tv_usec;         //microseconds

};

tz如果是NULL的话将不传递时区信息。tv提供秒为单位的和微妙为单位的从Epoch开始的计数。

结构体timeval的域为类型long的域。

此函数返回0,表示成功,-1表示失败。

 

Windows中,GetTickCount返回的是从系统启动到现在的毫秒。

int usleep(useconds_t usec);

定义在头文件unistd.h中。它使当前进程挂起至少usec微秒(百万分之一秒).睡眠时间可能会被任意系统活动或进程切换开销或系统计时器的精确度而轻微延迟。成功时返回0,错误时返回-1.

 

或者使用clock()来得到系统时间也是可以的。它返回从进程启动到现在经历的时间,单位是毫秒(千分之一秒)。定义在头文件time.h下.

           clock_t clock(void);

相应代码如下。


 

[cpp] view plaincopyprint?
  1. #include <time.h>  
  2. #include <sys/time.h>  
  3. #include <unistd.h>  
  4. #include<stdlib.h>  
  5. #include<math.h>  
  6.   
  7. #define DWORD unsigned long  
  8. #define UINT64 unsigned long long  
  9. const double SPLIT = 0.01;  
  10. const int COUNT = 200;  
  11. const double PI = 3.14159265;  
  12. const int INTERVAL = 300;  
  13.   
  14. int main(int argc, char* argv[] )  
  15. {  
  16.     struct timeval tms;  
  17.     DWORD busySpan[COUNT];  
  18.     DWORD idleSpan[COUNT];  
  19.     int half = INTERVAL/2, i;  
  20.     double radian = 0.0;  
  21.     for(i = 0; i < COUNT; ++i)  
  22.     {  
  23.         busySpan[i] = (DWORD)(half + (sin(PI * radian) * half));  
  24.         idleSpan[i] = INTERVAL - busySpan[i];  
  25.         radian += SPLIT;  
  26.     }  
  27.     clock_t startTime = 0;  
  28.     int j = 0;  
  29.     while(1)  
  30.     {  
  31.         j = j % COUNT;  
  32.         timerclear(&tms);  
  33.         gettimeofday(&tms,NULL);  
  34.         clock_t startTime = clock();  
  35.         while((clock()-startTime) <= busySpan[j])//clock返回该进程从启动到现在经历的毫秒数(千分之一秒)  
  36.         ;  
  37.         if(usleep(idleSpan[j]*1000))  //精确到微秒(百万分之一秒)的函数  
  38.                 exit(-1);  
  39.         j++;  
  40.     }  
  41.     return 0;  
  42. }  

但对于多核CPU,如何限制进程在一个CPU上运行呢?

 

如何察看某个进程在哪个CPU上运行:

在控制台中输入:

#top -d 1

之后按下f.进入top Current Fields设置页面:

选中:j: P          = Last used cpu (SMP)

则多了一项:P 显示此进程使用哪个CPU。

 

经过试验发现:同一个进程,在不同时刻,会使用不同CPU Core.这应该是Linux Kernel SMP处理的。

 

 

本程序通过这个方法查看,将会在多个CPU上运行。

想要让它在一个CPU上执行,可以这样做:

          1.下载包schedtool.

                    在控制台中输入:sudo apt-get install schedtool,然后输入你的密码。

schedtool是Linux下用来查询或设置CPU状态的工具。通过不同的参数可以查看或设置不同的属性。

<span style="font-size:18px;">[<strong>-0</strong>|<strong>-N</strong>] [<strong>-1</strong>|<strong>-F</strong>] [<strong>-2</strong>|<strong>-R</strong>] [<strong>-3</strong>|<strong>-B</strong>] [<strong>-4</strong>|<strong>-I</strong>] [<strong>-5</strong>|<strong>-D</strong>]        [<strong>-M</strong> <em>policy</em>]        [<strong>-a</strong> <em>affinity</em>]        [<strong>-p</strong> <em>prio</em>]        [<strong>-n</strong> <em>nice_level</em>]        [<strong>-e</strong> <em>command [arg ...]</em>]        [<strong>-r</strong>]        [<strong>-v</strong>]        [<strong>-h</strong>] </span>

我们这里要用到的是 -a和-e。其他可以参考这里:

http://linux.die.net/man/8/schedtool
-a用来设置进程在哪个CPU上运行。-a的参数为:
0x1  表示只运行在CPU0(00000001)
0x2 表示只运行在CPU1(00000010)
0x4表示紫云行在CPU2(00000100)
0x8表示只运行在CPU3(00001000)
etc.
或者,多CPU运行可以这样表示,
0x7表示可以运行在CPU0,1,2  (00000111)
0x5表示可运行在CPU0,2     (00000101)
以此类推。
-e用来通过指定的参数来执行命令。后面的参数为控制台命令。

 

在Linux下,如何确认是多核或多CPU:

#cat /proc/cpuinfo

如果有多个类似以下的项目,则为多核或多CPU:

processor       : 0

......

processor       : 1

 

在编译后,我们执行命令:sched -a 0x1 -e ./桌面/sin

可以通过上面介绍的方法查看进程sin是否在同一个CPU上运行。

然后就可以通过系统监视器查看运行结果啦!

运行结果(橙色线):

还有一段Python的代码,运行是与上面类似的,这个来自于网上^_^:

[python] view plaincopyprint?
  1. #!/usr/bin/env python  
  2. import itertools, math, time, sys  
  3.   
  4. time_period = float(sys.argv[1]) if len(sys.argv) > 1 else 30   # seconds  
  5. time_slice  = float(sys.argv[2]) if len(sys.argv) > 2 else 0.04 # seconds  
  6.   
  7. N = int(time_period / time_slice)  
  8. for i in itertools.cycle(range(N)):  
  9.     busy_time = time_slice / 2 * (math.sin(2*math.pi*i/N) + 1)  
  10.     t = time.clock() + busy_time  
  11.     while t > time.clock():  
  12.         pass  
  13.     time.sleep(time_slice - busy_time);  


在控制台下输入命令:sched -a 0x1 -e python ./桌面/sin_p.py(此处写你源文件的路径).即可!

 

版权声明:本文为博主原创文章,未经博主允许不得转载。


linux top & cset&schedtool对于多核CPU,如何限制进程在一个CPU上运行

(2013-05-30 18:02:14)
标签:

it

 
http://blog.csdn.net/rital/article/details/4363858

对于多核CPU,如何限制进程在一个CPU上运行呢?

   如何察看某个进程在哪个CPU上运行:

   在控制台中输入:

    #top -d1

   之后按下f.进入top Current Fields设置页面:

    选中:j:P         = Last used cpu (SMP)

    则多了一项:P显示此进程使用哪个CPU。

   经过试验发现:同一个进程,在不同时刻,会使用不同CPU Core.这应该是Linux Kernel SMP处理的。

本程序通过这个方法查看,将会在多个CPU上运行。

想要让它在一个CPU上执行,可以这样做:

         1.下载包schedtool.

                   在控制台中输入:sudo apt-get install schedtool,然后输入你的密码。

   schedtool是Linux下用来查询或设置CPU状态的工具。通过不同的参数可以查看或设置不同的属性。

    [-0|-N][-1|-F] [-2|-R] [-3|-B] [-4|-I] [-5|-D]

           [-M policy]

           [-a affinity]

           [-p prio]

           [-n nice_level]

           [-e command [arg ...]]

           [-r]

           [-v]

           [-h]

    我们这里要用到的是-a和-e。其他可以参考这里:

       http://linux.die.net/man/8/schedtool

       -a用来设置进程在哪个CPU上运行。-a的参数为:

       0x1  表示只运行在CPU0(00000001)

       0x2 表示只运行在CPU1(00000010)

       0x4表示紫云行在CPU2(00000100)

       0x8表示只运行在CPU3(00001000)

       etc.

       或者,多CPU运行可以这样表示,

       0x7表示可以运行在CPU0,1,2  (00000111)

       0x5表示可运行在CPU0,2    (00000101)

       以此类推。

       -e用来通过指定的参数来执行命令。后面的参数为控制台命令。

   在Linux下,如何确认是多核或多CPU:

    #cat/proc/cpuinfo

   如果有多个类似以下的项目,则为多核或多CPU:

   processor      : 0

   ......

   processor      : 1

在编译后,我们执行命令:sched -a 0x1 -e ./桌面/sin

可以通过上面介绍的方法查看进程sin是否在同一个CPU上运行。

然后就可以通过系统监视器查看运行结果啦!

运行结果(橙色线):

还有一段Python的代码,运行是与上面类似的,这个来自于网上^_^:

    #!/usr/bin/env python  import itertools, math, time, sys      time_period = float(sys.argv[1]) if len(sys.argv) > 1 else 30   # seconds      time_slice  = float(sys.argv[2]) if len(sys.argv) > 2 else 0.04 # seconds      N = int(time_period / time_slice)      for i in itertools.cycle(range(N)):          busy_time = time_slice / 2 * (math.sin(2*math.pi*i/N) + 1)          t = time.clock() + busy_time          while t > time.clock():              pass          time.sleep(time_slice - busy_time);

在控制台下输入命令:sched -a 0x1 -e python./桌面/sin_p.py(此处写你源文件的路径).即可!

suse real time quick start guide

1, CPU shield类型(3种)

* root: 包括所有可用CPUS

* system: 包括所有没有屏蔽的cpus

* user: 包括所有已经屏蔽的cpus

2, 查看cpu shield情况

rtdemo:~ # cset shield

cset: **> shielding not active on system

3, 创建user shield类型cpuset

rtdemo:~ # cset shield --cpu=1,3,5-7

cset: --> activating shielding:

cset: moving 132 tasks from root into system cpuset...

[==================================================]%

cset: "system" cpuset of CPUSPEC(0,2,4) with 132 tasksrunning

cset: "user" cpuset of CPUSPEC(1,3,5-7) with 0 tasks running

rtdemo:~ # cset shield

cset: --> shielding system active with

cset: "system" cpuset of CPUSPEC(0,2,4) with 132 tasksrunning

cset: "user" cpuset of CPUSPEC(1,3,5-7) with 0 tasks running

rtdemo:~ # ps aux | wc -l

299

4, 查看cpu shield情况

rtdemo:~ # cset shield --verbose

cset: --> shielding system active with

cset: "system"&n

 

1.cset shield -e -- schedtool-a 0x02 -e

  性能测试中,启动的程序最好绑定CPU的某个核shield,

  上面的参数

  -e executes args in theshield

  -a cpuset-name的第几个内核

注意:执行cset之前,先激活CPU内核 :cset shield--cpu=0,1,2,3

 

   2. schedtool -a0x02 -e command &

 

  root@stacknode8:/home/localadmin/node_modules/xx#cset shield -e --h
Usage: cset shield [options] [path/program]

Options:
  -c CPUSPEC, --cpu=CPUSPEC
                       modifies or initializes the shield cpusets
  -r,--reset          destroys the shield
  -e,--exec           executes args in the shield
 --user=USER          use this USER for --exec (id or name)
 --group=GROUP        use this GROUP for --exec (id or name)
  -s,--shield         shield specified PIDSPEC of processes or threads
  -u,--unshield       remove specified PIDSPEC of processes or threads from
                       shield
  -p PIDSPEC, --pid=PIDSPEC
                       specify pid or tid specification for shield/unshield
 --threads            if specified, any processes found in the PIDSPEC to
                       have multiple threads will automatically have all
                       their threads added to the PIDSPEC; use to affect all
                       related threads
  -k on|off, --kthread=on|off
                       shield from unbound interrupt threads as well
  -f,--force          force operation, use with care
  -v,--verbose        prints more detailed output, additive
 --sysset=SYSSET      optionally specify system cpuset name
 --userset=USERSET    optionally specify user cpuset name
  -h,--help           show this help message and exit

2.CPUAffinity的设置,到底在系统中会有什么样的积极影响,切换cpu和限制在同一个cpu上到底会让一个进程的效率有什么改变,为此做了一些研究,结论如下:

  1. CPUCache可以在绑定的情况下,提高命中率。如果一个线程在多个Processor中来回切换,可能会导致CPU的cache持续失效
  2. 如果多个线程访问的数据相同,设置同样的Affinity Mask可以帮助这个Processor提高命中
  3. 可以让一些需要高优先级的Process独享一个Processor。通过将系统其他的Process绑定到一个processor上,并将高优先级的Process绑定到空闲的Processor上

对于一个开发者来说,他可以直接使用Linux内核2.5.8版本以后提供的API函数,用来设置自己进程的AffinityMask,但是对于系统程序或者不是自己开发的进程怎么办。如果我们不能设置第三方程序的Mask,那么上文的第三点,让某个进程独享一个Processor就无法实现了。

Debian提供了一个工具:schedtool(其他发行版还没有验证),可以使用他来设置一个pid的AffinityMask。不过想要把系统所有的进程全部都设置一遍,非常的没有效率。这里有一个简单的办法,因为AffinityMask的设置是继承的,子进程会沿用父进程的Mask,我们只需要在系统的启动文件中,将pid为1的系统启动进程设置成我们想要的mask,那么后面的所有系统服务就可以继承这个值了。

修改 /etc/rc.sysinit 在最前方添加

/bin/schedtool -a 0x1 1/bin/schedtool -a 0x1 $$

这样可以将pid为1和当前的进程的AffinityMask设置为1,也就是说只能使用第0号内核。这样,如果假设我们系统有四个核心,我们希望第一个个核心用来跑操作系统自己的相关进程和服务,后面三个核心各跑一个我们自己的服务,就只需要在自己的服务启动之后,再使用bind命令修改他们的Mask即可。

root@stacknode9:/home/localadmin/node_modules/xx#schedtool -h
get/set scheduling policies - v1.3.0, GPL'd, NO WARRANTY
USAGE: schedtoolPIDS                   - query PIDS
      schedtool [OPTIONS]PIDS         - set PIDS
      schedtool [OPTIONS] -eCOMMAND    -exec COMMAND

set scheduling policies:
   -N                   for SCHED_NORMAL
    -F -pPRIO           forSCHED_FIFO      only as root
    -R -pPRIO           forSCHED_RR        only as root
   -B                   for SCHED_BATCH
    -I -pPRIO           for SCHED_ISO
   -D                   for SCHED_IDLEPRIO

    -MPOLICY            for manual mode; raw number for POLICY
    -pSTATIC_PRIORITY   usually 1-99; only for FIFO or RR
                         higher numbers means higher priority
    -nNICE_LEVEL        set niceness to NICE_LEVEL
    -aAFFINITY_MASK     set CPU-affinity to bitmask or list

    -eCOMMAND[ARGS]    start COMMAND with specified policy/priority
   -r                   display priority min/max for each policy
   -v                   be verbose

----------------------------------------------------------------------------------------------

3.TOP是一个动态显示过程,即可以通过用户按键来不断刷新当前状态.如果在前台执行该命令,它将独占前台,直到用户终止该程序为止.比较准确的说,top命令提供了实时的对系统处理器的状态监视.它将显示系统中CPU最“敏感”的任务列表.该命令可以按CPU使用.内存使用和执行时间对任务进行排序;而且该命令的很多特性都可以通过交互式命令或者在个人定制文件中进行设定.
top - 12:38:33 up 50 days, 23:15,  7users,  load average: 60.58, 61.14, 61.22

Tasks: 203 total,  60 running, 139sleeping,   4stopped,   0 zombie

Cpu(s)  : 27.0%us, 73.0%sy, 0.0%ni,  0.0%id, 0.0%wa,  0.0%hi, 0.0%si,  0.0%st

Mem:   1939780ktotal,  1375280kused,   564500kfree,   109680k buffers

Swap:  4401800ktotal,   497456kused,  3904344kfree,   848712k cached

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

 4338oracle   25   627m209m 207m R    011.0 297:14.76oracle                               

 4267oracle   25   626m144m 143m R    7.6  89:16.62oracle                               

 3458oracle   25   672m133m 124m R    7.1   1283:08oracle                               

 3478oracle   25   672m124m 115m R    6.6   1272:30oracle                               

 3395oracle   25   672m122m 113m R    6.5   1270:03oracle                                

 3480oracle   25   672m122m 109m R    6.4   1274:13oracle                               

 3399oracle   25   672m121m 110m R    6.4   1279:37oracle                               

 4261oracle   25   634m100m  99mR    5.3  86:13.90oracle                               

25737oracle   25  632m  81m  74mR    4.3 272:35.42oracle                               

 7072oracle   25  626m  72m  71mR    3.8   6:35.68oracle                               

16073oracle   25  630m  68m  63mR    3.6 175:20.36oracle                               

16140oracle   25  630m  66m  60mR    3.5 175:13.42oracle                               

16122oracle   25  630m  66m  60mR    3.5 176:47.73oracle                               

  786oracle   25  627m  63m  63mR    3.4   1:54.93oracle                               

 4271oracle   25  627m  59m  58mR    3.1  86:09.64oracle                               

 4273oracle   25  627m  57m  56mR    3.0  84:38.20oracle                               

22670oracle   25  626m  50m  49mR    2.7  84:55.82oracle    

一.  TOP前五行统计信息

统计信息区前五行是系统整体的统计信息。

1. 第一行是任务队列信息

同 uptime  命令的执行结果:

[root@localhost ~]# uptime

 13:22:30 up 8 min,  4users,  load average: 0.14, 0.38, 0.25

其内容如下:

12:38:33
 当前时间
 
up 50days
 系统运行时间,格式为时:分
 
1 user
 当前登录用户数
 
load average: 0.06, 0.60, 0.48
 系统负载,即任务队列的平均长度。 三个数值分别为 1分钟、5分钟、15分钟前到现在进程的平均值。
 

2. 第二、三行为进程和CPU的信息

当有多个CPU时,这些内容可能会超过两行。内容如下:

Tasks: 29 total
 进程总数
 
1 running
 正在运行的进程数
 
28 sleeping
 睡眠的进程数
 
0 stopped
 停止的进程数
 
0 zombie
 僵尸进程数
 
Cpu(s): 0.3% us
 用户空间占用CPU百分比
 
1.0% sy
 内核空间占用CPU百分比
 
0.0% ni
 用户进程空间内改变过优先级的进程占用CPU百分比
 
98.7% id
 空闲CPU百分比
 
0.0% wa
 等待输入输出的CPU时间百分比
 
0.0% hi
 
0.0% si
 

3. 第四五行为内存信息。

内容如下:

Mem: 191272k total
 物理内存总量
 
173656k used
 使用的物理内存总量
 
17616k free
 空闲内存总量
 
22052k buffers
 用作内核缓存的内存量
 
Swap: 192772k total
 交换区总量
 
0k used
 使用的交换区总量
 
192772k free
 空闲交换区总量
 
123988k cached
 缓冲的交换区总量。内存中的内容被换出到交换区,而后又被换入到内存,但使用过的交换区尚未被覆盖,该数值即为这些内容已存在于内存中的交换区的大小。相应的内存再次被换出时可不必再对交换区写入。
 

二.  进程信息

列名
 含义
 
PID
 进程id
 
PPID
 父进程id
 
RUSER
 Real user name
 
UID
 进程所有者的用户id
 
USER
 进程所有者的用户名
 
GROUP
 进程所有者的组名
 
TTY
 启动进程的终端名。不是从终端启动的进程则显示为 ?
 
PR
 优先级
 
NI
 nice值。负值表示高优先级,正值表示低优先级
 
P
 最后使用的CPU,仅在多CPU环境下有意义
 
%CPU
 上次更新到现在的CPU时间占用百分比
 
TIME
 进程使用的CPU时间总计,单位秒
 
TIME+
 进程使用的CPU时间总计,单位1/100秒
 
%MEM
 进程使用的物理内存百分比
 
VIRT
 进程使用的虚拟内存总量,单位kb。VIRT=SWAP+RES
 
SWAP
 进程使用的虚拟内存中,被换出的大小,单位kb。
 
RES
 进程使用的、未被换出的物理内存大小,单位kb。RES=CODE+DATA
 
CODE
 可执行代码占用的物理内存大小,单位kb
 
DATA
 可执行代码以外的部分(数据段+栈)占用的物理内存大小,单位kb
 
SHR
 共享内存大小,单位kb
 
nFLT
 页面错误次数
 
nDRT
 最后一次写入到现在,被修改过的页面数。
 
S
 进程状态。
           D=不可中断的睡眠状态
           R=运行
           S=睡眠
           T=跟踪/停止
           Z=僵尸进程
 
COMMAND
 命令名/命令行
 
WCHAN
 若该进程在睡眠,则显示睡眠中的系统函数名
 
Flags
 任务标志,参考 sched.h
  在系统维护的过程中,随时可能有需要查看 CPU 使用率,并根据相应信息分析系统状况的需要。在CentOS 中,可以通过 top 命令来查看 CPU 使用状况。运行 top 命令后,CPU使用状态会以全屏的方式显示,并且会处在对话的模式 – 用基于 top 的命令,可以控制显示方式等等。退出 top 的命令为 q (在top 运行中敲 q 键一次)。

 

 在命令行中输入 “top” 即可启动 top 。

    top 的全屏对话模式可分为3部分:系统信息栏、命令输入栏、进程列表栏。

 

   第一部分 -- 最上部的 系统信息栏 :   

   第一行(top): “00:11:04”为系统当前时刻;  “3:35”为系统启动后到现在的运作时间;    “2users”为当前登录到系统的用户,更确切的说是登录到用户的终端数 --同一个用户同一时间对系统多个终端的连接将被视为多个用户连接到系统,这里的用户数也将表现为终端的数目;  “loadaverage”为当前系统负载的平均值,后面的三个值分别为1分钟前、5分钟前、15分钟前进程的平均数,一般的可以认为这个数值超过CPU 数目时,CPU 将比较吃力的负载当前系统所包含的进程;   

   第二行(Tasks): “59 total”为当前系统进程总数;“1 running”为当前运行中的进程数;“58sleeping”为当前处于等待状态中的进程数;“0 stoped”为被停止的系统进程数;“0 zombie”为被复原的进程数;  

   第三行(Cpus):分别表示了 CPU 当前的使用率;   

   第四行(Mem):分别表示了内存总量、当前使用量、空闲内存量、以及缓冲使用中的内存量;   

   第五行(Swap):表示类别同第四行(Mem),但此处反映着交换分区(Swap)的使用情况。通常,交换分区(Swap)被频繁使用的情况,将被视作物理内存不足而造成的。

 

   第二部分 -- 中间部分的内部命令提示栏:   top 运行中可以通过 top 的内部命令对进程的显示方式进行控制。内部命令如下表:  s - 改变画面更新频率  l - 关闭或开启第一部分第一行 top 信息的表示  t - 关闭或开启第一部分第二行 Tasks和第三行 Cpus 信息的表示  m - 关闭或开启第一部分第四行 Mem 和 第五行 Swap 信息的表示  N - 以 PID的大小的顺序排列表示进程列表(第三部分后述)  P - 以 CPU 占用率大小的顺序排列进程列表 (第三部分后述)  M -以内存占用率大小的顺序排列进程列表 (第三部分后述)  h - 显示帮助  n - 设置在进程列表所显示进程的数量  q - 退出top   s - 改变画面更新周期。

    第三部分 -- 最下部分的进程列表栏:   以 PID区分的进程列表将根据所设定的画面更新时间定期的更新。通过 top 内部命令可以控制此处的显示方式。

top 的man 命令解释如下:

    Listedbelow are top's available fields.  They are alwaysassociated with the  letter shown,  regardless  of theposition you may have established for them with the 'o' (Orderfields) interactive command.Any field is selectable as the sortfield, and you control whether they are  sortedhigh-to-low  or low-to-high.  For  additional  information onsort provisions see  topic 3c. TASK AreaCommands.

a: PID  --  Process Id

      The task's unique process ID, which periodically wraps, thoughnever  restarting at zero.

b: PPID  --  Parent ProcessPid

      The process ID of a task's parent.

c: RUSER  --  Real UserName

      The real user name of the task's owner.

d: UID  --  User Id

      The effective user ID of the task's owner.

e: USER  --  User Name

      The effective user name of the task's owner.

f: GROUP  --  Group Name

      The effective group name of the task's owner.

g: TTY  --  ControllingTty

      The  name of the controllingterminal.  This is usually the device (serialport, pty, etc.) from which the process was started, and which ituses  for input oroutput.  However,  a task need not be associated with aterminal, in which case you'll see '?' displayed.

h: PR  --  Priority

      The priority of the task.

i: NI  --  Nice value

      The nice value of the task.   negative nice  value means  higher  priority,whereas  positive nice valuemeans lower priority.  Zero in this field simplymeans priority will not be adjusted in determining a task'sdispatchability.

j: P  --  Last used CPU(SMP)

      A number representing the last used processor.  Ina true SMP  environment  thiswill likely change frequently since the kernel intentionally usesweak affinity. Also, the very act of running top may break thisweak affinity  and cause  more processes  to changeCPUs more often (because of the extra demand for cpu time).

k: %CPU  --  CPU usage

      The task's share of the elapsed CPU time since the last screenupdate, expressed as a percentage of total CPUtime.  In a true SMP environment, if 'Irix mode'is Off, top will operate in 'Solaris mode' where a task's cpu usagewill be divided by  the total  number of  CPUs.   Youtoggle 'Irix/Solaris' modes with the 'I' interactive command.

l: TIME  --  CPU Time

      Total CPU time the task has used since itstarted.  When 'Cumulative  mode'  isOn,  each  process is listed withthe cpu time that it and its dead children hasused.  You toggle 'Cumulative mode' with 'S',which is a command-line option and an interactivecommand.  See the 'S' interactive command foradditional information regarding this mode.

m: TIME+  --  CPU Time,hundredths

      The same as 'TIME', but reflecting more granularity throughhundredths of asec         ond.

n: %MEM  --  Memory usage(RES)

      A task's currently used share of available physical memory.

o: VIRT  --  Virtual Image(kb)

      The total amount of virtual memory used by thetask.  It includes all code, data and sharedlibraries plus pages that have been  swapped out.  (Note: you  can define  the STATSIZE=1environment variable and the VIRT will be calculated from the/proc/#/state VmSize field.)

      VIRT = SWAP + RES.

p: SWAP  --  Swapped size(kb)

      The swapped out portion of a task's total virtual memory image.

q: RES  --  Resident size(kb)

      The non-swapped physical memory a task has used.

      RES = CODE + DATA.

r: CODE  --  Code size(kb)

      The amount of physical memory devoted toexecutable  code, also  known  as the'text resident set' size or TRS.

s: DATA  --  Data+Stack size(kb)

      The  amount of physical memory devoted to otherthan executable code, also known the 'data resident set' size orDRS.

t: SHR  --  Shared Mem size(kb)

      The amount of shared memory used by atask.   It simply  reflects memory  that could be potentially shared withother processes.

u: nFLT  --  Page Faultcount

      The  number  of major  page faults that have occurred for atask.  A page fault occurs when a process attemptsto read from or write to a virtual page that  is not currently  present in  its address space.  A majorpage fault is when disk access is involved in making that pageavailable.

v: nDRT  --  Dirty Pagescount

      The number of pages that have been modified since they  were last  written  todisk.   Dirty pages  must  be written to diskbefore the corresponding physical memory location can be used forsome other virtual page.

w: S  --  Process Status

      The status of the task which can be one of:

            'D' = uninterruptible sleep

            'R' = running

            'S' = sleeping

            'T' = traced or stopped

            'Z' = zombie

      Tasks shown as running should be more properly thought of as 'readyto run'  --their  task_struct issimply represented on the Linux run-queue.  Evenwithout a true SMP machine, you may see numerous tasks in thisstate  depending on  top's delay interval and nice value.

x: Command  --  Command lineor Program name

      Display the command line used to start a task or the name of theassociated program.  You toggle between commandline and name with 'c', which is both  command-line option and an interactive command.When  you've chosen  to display command lines, processeswithout a command line (like kernel threads) will be shown withonly the program name  in parentheses, as in thisexample:               ( mdrecoveryd ) Either  form of  display is subject to potential truncation ifit's too long to fit in this field's current width.   That width  depends upon  other fields  selected, their order and the currentscreen width.

      Note: The 'Command' field/column is unique, in that it is notfixed-width.  When displayed, this column will beallocated all remaining screen width (up to  the maximum 512  characters) to  provide for the potential growth of programnames into command lines.

y: WCHAN  --  Sleeping inFunction

      Depending on the availability of the kernel link map('System.map'), this  field will show  the  name or the address ofthe kernel function in which the task is currentlysleeping.  Running tasks will display a dash ('-')in this column.

      Note: By displaying this field, top's own working set will beincreased by  over700Kb.   Your only  means of reducing that overhead will be tostop andrestart         top.

z: Flags  --  Task Flags

      This column represents the task's current scheduling flagswhich  are  expressedin  hexadecimal  notation andwith zeros suppressed.  These flags are officiallydocumented in .  Less formal documentation canalso be  found  on the 'Fieldsselect' and 'Order fields' screens.

      默认情况下仅显示比较重要的 PID、USER、PR、NI、VIRT、RES、SHR、S、%CPU、%MEM、TIME+、COMMAND 列。

2.1 用快捷键更改显示内容。
(1)更改显示内容通过 f键可以选择显示的内容。

      按 f 键之后会显示列的列表,按 a-z  即可显示或隐藏对应的列,最后按回车键确定。

(2)按o键可以改变列的显示顺序。

      按小写的 a-z 可以将相应的列向右移动,而大写的 A-Z 可以将相应的列向左移动。最后按回车键确定。

      按大写的 F 或 O 键,然后按 a-z 可以将进程按照相应的列进行排序。而大写的  R键可以将当前的排序倒转。

      设置完按回车返回界面。

注意:

进程top -c -d 5>/tmp/cpu.txt   linux <wbr>top <wbr>& <wbr>cset&schedtool对于多核CPU,如何限制进程在一个CPU上运行 每5s显示一下内存信息

grep -i 进程名 /tmp/cpu.txt |/tmp/cpu-01.txt  查找相关进程的CPU内存使用到一个文件

 

三.  命令使用

详细内容可以参考MAN 帮助文档。这里列举部分内容:

命令格式:

top [-] [d] [p] [q] [c] [C][S]    [n]

参数说明:

d:  指定每两次屏幕信息刷新之间的时间间隔。当然用户可以使用s交互命令来改变之。

p:  通过指定监控进程ID来仅仅监控某个进程的状态。

q:该选项将使top没有任何延迟的进行刷新。如果调用程序有超级用户权限,那么top将以尽可能高的优先级运行。

S: 指定累计模式

s : 使top命令在安全模式中运行。这将去除交互命令所带来的潜在危险。

i:  使top不显示任何闲置或者僵死进程。

c:  显示整个命令行而不只是显示命令名

在top命令的显示窗口,我们还可以输入以下字母,进行一些交互:

帮助文档如下:

Help for Interactive Commands - procps version 3.2.7

Window 1:Def: Cumulative mode Off.  System:Delay 4.0 secs; Secure mode Off.

 Z,B      Global: 'Z' change color mappings; 'B' disable/enable bold

 l,t,m    Toggle Summaries: 'l' load avg; 't' task/cpu stats; 'm' meminfo

 1,I      Toggle SMP view: '1' single/separate states; 'I' Irix/Solarismode

 f,o    . Fields/Columns: 'f' add or remove; 'o' change display order

  F or O  . Select sortfield

 <,>    . Move sort field: '<' next col left; '>' next col right

 R,H    . Toggle: 'R' normal/reverse sort; 'H' show threads

  c,i,S   .Toggle: 'c' cmd name/line; 'i' idle tasks; 'S' cumulative time

 x,y    . Toggle highlights: 'x' sort field; 'y' running tasks

 z,b    . Toggle: 'z' color/mono; 'b' bold/reverse (only if 'x' or 'y')

      . Show specific user only

  n or #  . Set maximum tasksdisplayed

 k,r      Manipulate tasks: 'k' kill; 'r' renice

  d ors    Set updateinterval

        Write configuration file

        Quit

         ( commands shown with '.' require a visible task display window)

Press 'h' or '?' for help with Windows,

h或者?  : 显示帮助画面,给出一些简短的命令总结说明。

:终止一个进程。系统将提示用户输入需要终止的进程PID,以及需要发送给该进程什么样的信号。一般的终止进程可以使用15信号;如果不能正常结束那就使用信号9强制结束该进程。默认值是信号15。在安全模式中此命令被屏蔽。

i:忽略闲置和僵死进程。这是一个开关式命令。

q:  退出程序。

r: 重新安排一个进程的优先级别。系统提示用户输入需要改变的进程PID以及需要设置的进程优先级值。输入一个正值将使优先级降低,反之则可以使该进程拥有更高的优先权。默认值是10。

S:切换到累计模式。

s : 改变两次刷新之间的延迟时间。系统将提示用户输入新的时间,单位为s。如果有小数,就换算成ms。输入0值则系统将不断刷新,默认值是5s。需要注意的是如果设置太小的时间,很可能会引起不断刷新,从而根本来不及看清显示的情况,而且系统负载也会大大增加。

f或者F :从当前显示中添加或者删除项目。

o或者O  :改变显示项目的顺序。

l: 切换显示平均负载和启动时间信息。即显示影藏第一行

m: 切换显示内存信息。即显示影藏内存行

t : 切换显示进程和CPU状态信息。即显示影藏CPU行

c:  切换显示命令名称和完整命令行。 显示完整的命令。 这个功能很有用。

M : 根据驻留内存大小进行排序。

P:根据CPU使用百分比大小进行排序。

T: 根据时间/累计时间进行排序。

W:  将当前设置写入~/.toprc文件中。这是写top配置文件的推荐方法。


taskset编辑

本词条缺少信息栏名片图,补充相关内容使词条更完整,还能快速升级,赶紧来编辑吧!
taskset 是 Linux 系统当中,用于查看、设定 CPU 核使用情况的命令。
他属于 util-linux-ng 包,若您的系统中没有这个命令,可以通过安装这个包来增加这个命令。

目录

1命令定义

2命令描述

3参数描述

4使用帮助

5权限要求

6获取软件

7参考命令

1命令定义编辑

taskset [options] mask command [arg]...
taskset [options] -p [mask] pid

2命令描述编辑

taskset 命令用于设置或者获取一直指定的 PID 对于 CPU 核的运行依赖关系。也可以用 taskset 启动一个命令,直接设置它的 CPU 核的运行依赖关系。
CPU 核依赖关系是指,命令会被在指定的 CPU 核中运行,而不会再其他 CPU 核中运行的一种调度关系。需要说明的是,在正常情况下,为了系统性能的原因,调度器会尽可能的在一个 CPU 核中维持一个进程的执行。强制指定特殊的 CPU 核依赖关系对于特殊的应用是有意义的。
CPU 核的定义采用位定义的方式进行,最低位代表 CPU0,然后依次排序。这种位定义可以超过系统实际的 CPU 总数,并不会存在问题。通过命令获得的这种 CPU 位标记,只会包含系统实际 CPU 的数目。如果设定的位标记少于系统 CPU 的实际数目,那么命令会产生一个错误。当然这种给定的和获取的位标记采用 16 进制标识。
0x00000001
代表 #0 CPU
0x00000003
代表 #0 和 #1 CPU
0xFFFFFFFF
代表 #0 到 #31 CPU

3参数描述编辑

-p, --pid
对一个现有的进程进行操作,而不是启动一个新的进程
-c, --cpu-list
使用 CPU 编号替代位标记,这可以是一个列表,列表中可以使用逗号分隔,或者使用 "-" 进行范围标记,例如:0,5,7,9-11
-h, --help
打印帮助信息
-V, --version
打印版本信息

4使用帮助编辑

  • 使用默认的行为,用给定的 CPU 核运行位标记运行一个进程
    taskset mask command [arguments]
  • 获取一个指定进程的 CPU 核运行位标记
    taskset -p pid
  • 设定一个指定进程的 CPU 核运行位标记
    taskset -p mask pid

5权限要求编辑

如果需要设定,那么需要拥有 CAP_SYS_NICE 的权限;如果要获取设定信息,没有任何权限要求。

6获取软件编辑

taskset 命令属于 util-linux-ng 包,可以使用 yum 直接安装。

7参考命令编辑

chrt, nice, renice, sched_setaffinity, sched_getaffinity

0 0
原创粉丝点击