如何限制CPU资源的使用率
在我们运维的db环境中,一个机器跑多个mysql实例经常会出现某个进程占用了几乎所有的cpu 进而影响其他的实例运行。基于此我们需要限制某个进程的cpu资源,将其使用 的cpu限定在某个或者某几个固定的cpu上,避免对其他的进程产生影响。
限制cpu的方法有以下几种:
- taskset
- cpulimit
- 使用nice和 设置程序执行的优先级
- 使用ulimit 限制cpu
下面着重介绍taskset cpulimit 的方法。方法 3 4 在现有环境中操作性不强。
taskset
1 2 | -p,--pid 对一个已存在的pid进行操作 -c,--cpu-list 限定进程到指定的cpu上,可以指定多个,以逗号分隔,也可指定范围:1,2,5,6-8。 |
a 使用 top 获取占用cpu 资源最多的进程。
1 2 3 4 5 6 7 8 9 | 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
1 2 3 | [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 安装
1 2 3 | [root@rac1 ~]# svn checkout cpulimit [root@rac1 ~]# cd cpulimit/ [root@rac1 cpulimit]# make |
b 使用
1 2 3 4 5 6 7 | 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 是限定某个进程的使用 cpu使用率,而非像taskset 绑定某个进程到指定的cpu上面。cpulimit的具体用法 详见cpulimit --help