现在的位置: 首页 > 综合 > 正文

linux 如何控制cpu资源使用

2017年08月10日 ⁄ 综合 ⁄ 共 2762字 ⁄ 字号 评论关闭
  在我们运维的db环境中,一个机器跑多个mysql实例经常会出现某个进程占用了几乎所有的cpu 进而影响其他的实例运行。基于此我们需要限制某个进程的cpu资源,将其使用 的cpu限定在某个或者某几个固定的cpu上,避免对其他的进程产生影响。


限制cpu的方法有以下几种:

1 taskset

2 cpulimit

3 使用nice和renice设置程序执行的优先级

4 使用ulimit 限制cpu  
下面着重介绍taskset cpulimit 的方法。 方法 3 4 在现有环境中操作性不强。
一 taskset 

-p,--pid      对一个已存在的pid进行操作

-c,--cpu-list  限定进程到指定的cpu上,可以指定多个,以逗号分隔,也可指定范围:1,2,5,6-8。


a 使用 top 获取占用cpu 资源最多的进程。

top - 21:23:41 up 318 days, 23:00,  4 users,  load average: 3.79, 3.77, 3.67

Tasks: 202 total,   2 running, 200 sleeping,   0 stopped,   0 zombie

Cpu0  : 55.0%us, 12.7%sy,  0.0%ni, 15.7%id, 16.7%wa,  0.0%hi,  0.0%si,  0.0%st

Cpu1  : 55.7%us, 12.7%sy,  0.0%ni, 17.7%id, 12.7%wa,  0.3%hi,  1.0%si,  0.0%st

Mem:   4044720k total,  4019124k used,    25596k free,    50820k buffers

Swap:  4192956k total,  2091956k used,  2101000k free,  1625080k cached


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

19041 mysql     18   0 2621m 2.0g 5148 S 119.4 50.8 439:34.34 mysqld


b 使用 taskset 将19041 绑定到 核1

[root@rac1 ~]# taskset  -pc 1 19041

pid 19041's current affinity list: 0,1

pid 19041's new affinity list: 1

二 使用 cpulimit 对cpu进行限定

     cpulimit is a simple program that attempts to limit the cpu usage of a process (expressed in percentage, not in cpu time). This is useful to control batch jobs, when you don't want them
to eat too much cpu. It does not act on the nice value or other scheduling priority stuff, but on the real cpu usage. Also, it is able to adapt itself to the overall system load, dynamically and quickly.



a 安装

[root@rac1 ~]# svn checkout https://cpulimit.svn.sourceforge.net/svnroot/cpulimit/trunk cpulimit

[root@rac1 ~]# cd cpulimit/

[root@rac1 cpulimit]# make

b 使用

cpulimit 参数   目标进程 

Usage: cpulimit [OPTIONS...] TARGET

  参数

      -l, --limit=N          限定cpu使用率范围 0-200 %

  目标进程必须有以下参数限定:

      -p, --pid=N            pid of the process (implies -z)

      -e, --exe=FILE         name of the executable program file or path name

测试场景  开启一个tpcc 压测模型 对mysql 进程进行压测使其cpu使用率达到满负荷
使用cpu进行限制之前
使用cpulimit -e mysqld -l 70 -z -v 命令对mysqld进程进行限制
使用cpulimit 限制之后

需要说明的是 cpulimit 是限定某个进程的使用 cpu使用率,而非像taskset 绑定某个进程到指定的cpu上面。cpulimit的具体用法 详见cpulimit --help
 

三 使用nice和renice设置程序执行的优先级

格式:nice [-n 数值] 命令

nice 指令可以改变程序执行的优先权等级。指令让使用者在执行程序时,指定一个优先等级,称之为 nice 值。这个数值从最高优先级的-20到最低优先级的19。负数值只有 root 才有权力使。一般使用者,也可使用 nice 指令來做执行程序的优先级管理,但只能将nice值越调越高。

可以通过二种方式来给某个程序设定nice值:

1 用nice命令为开始执行程序设置一个nice值,如 nice 2  sh  backup.sh & 

2 如果调整某个运行中程序的PID的nice值,则用renice命令

四  使用ulimit 
在linux中,使用ulimit可以限制SHELL中的资源使用。ulimit 用于限制 shell 启动进程所占用的资源,支持以下各种类型的限制:

a 所创建的内核文件的大小、
b 进程数据块的大小、
c Shell 进程创建文件的大小、
d 内存锁住的大小、
e 常驻内存集的大小、
f 打开文件描述符的数量、
g 分配堆栈的最大大小、
h CPU 时间、
i 单个用户的最大线程数、
j Shell 进程所能使用的最大虚拟内存。
k 支持硬资源和软资源的限制。
注意:ulimit只对当前shell有效. 


参考资料:
推荐 前面两个。


抱歉!评论已关闭.