CPU资源的简单调优
要对一个系统进行优化,查找瓶颈来自哪个方面是关键,虽然看似是某一个子系统出现问题,其实有可能是别的子系统导致的。调优就像医生看病,因此需要你对服务器所有地方都了解清楚
1)调整nice值改变进程优先级
在Linux系统中,nice值的范围从-20到+19(不同系统的值范围是不一样的),正值表示低优先级,负值表示高优先级,值为零则表示不会调整该进程的优先级。具有最高优先级的程序,其nice值最低,所以在Linux系统中,值-20使得一项任务变得非常重要;与之相反,如果任务的nice为+19,则表示它是一个高尚的、无私的任务,允许所有其他任务比自己享有宝贵的CPU时间的更大使用份额,这也就是nice的名称的来意。默认优先级是0。
可以在运行命令前,设置进程的nice值,让进程使用更多的CPU。nice -n [nice值] [完整命令]
nginx
还可以使用renice修改当前进程的nice值。renice -n [nice值] [PID]
[root@centos7 ~]# ps -ef|grep nginx root 995 1 0 20:31 ? 00:00:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf nginx 996 995 0 20:31 ? 00:00:00 nginx: worker process nginx 997 995 0 20:31 ? 00:00:00 nginx: worker process [root@centos7 ~]# renice -n -20 995 #996 997 #重启服务任然生效 995 (进程 ID) 旧优先级为 0,新优先级为 -20 top -p 995 PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 995 root 0 -20 28224 672 220 S 0.0 0.0 0:00.00 nginx
2)设置进程的CPU亲和力(指定进程运行在哪一个CPU上)
使用的是taskset命令,安装的是util-linux。taskset在多核的情况下,可以指定进程在那个CPU上运行,减少进程在不同CPU之间切换的开销。
taskset -c 1 vim ge.txt [root@centos7 ~]# ps aux | grep vim root 1696 0.1 0.1 149636 5172 pts/0 S+ 20:55 0:00 vim ge.txt root 1700 0.0 0.0 112824 988 pts/2 S+ 20:55 0:00 grep --color=auto vim [root@centos7 ~]# taskset -cp 1696 pid 1696's current affinity list: 1
查看cpu运行在那个核上 taskset -cp PID
[root@centos7 ~]# ps axu | grep sshd root 973 0.0 0.1 112900 4312 ? Ss 20:31 0:00 /usr/sbin/sshd -D root 1480 0.0 0.1 161512 6112 ? Ss 20:33 0:00 sshd: root@pts/0,pts/1,pts/2 root 1704 0.0 0.0 112824 984 pts/2 S+ 20:57 0:00 grep --color=auto sshd [root@centos7 ~]# taskset -cp 973 pid 973's current affinity list: 0,1 [root@centos7 ~]# taskset -cp 1480 pid 1480's current affinity list: 0,1
yum -y install util-linux
yum -y install sysstat
[root@centos7 ~]# mpstat -P ALL Linux 3.10.0-1160.el7.x86_64 (centos7) 2022年04月16日 _x86_64_ (2 CPU) 20时47分55秒 CPU %usr %nice %sys %iowait %irq %soft %steal %guest %gnice %idle 20时47分55秒 all 0.22 0.00 0.99 0.07 0.00 0.11 0.00 0.00 0.00 98.62 20时47分55秒 0 0.14 0.00 0.88 0.02 0.00 0.17 0.00 0.00 0.00 98.80 20时47分55秒 1 0.30 0.00 1.11 0.11 0.00 0.05 0.00 0.00 0.00 98.43
[root@centos7 ~]# taskset -cp 995 pid 995's current affinity list: 0,1 [root@centos7 ~]# taskset -cp 996 pid 996's current affinity list: 0 [root@centos7 ~]# taskset -cp 997 pid 997's current affinity list: 1
当然也可以设置命令在多个CPU上运行,CPU编号之间用逗号隔开。 taskset -c 0,1 vim eeee.txt