nginx|nginx性能优化_CPU亲和

【nginx|nginx性能优化_CPU亲和】
为什么要绑定 Nginx 进程到不同的 CPU 上?

默认情况下,Nginx 的多个进程有可能跑在某一个 CPU 或 CPU 的某一核上,导致 Nginx 进程使用硬件的资源不均,因此绑定 Nginx 进程到不同的 CPU 上是为了充分利用硬件的多 CPU 多核资源的目的。不同worker的工作进程绑定到不同的CPU上,减少不同的worker间切换CPU的频率,减小性能损耗

查看cpu数及cpu核心数:
#查看cpu个数 [root@zq]# grep -c processor /proc/cpuinfo 4#有4个物理cpu [root@zq]# cat /proc/cpuinfo| grep 'physical id' | sort|uniq|wc -l 4#单cpu有1个cpu核心 [root@zq]# cat /proc/cpuinfo| grep 'cpu cores'|uniq cpu cores: 1总共有4*1=4个核心[root@zq]# top#top命令,再按键盘上的“1”,显示当前核心的数量 top - 20:25:59 up 38 days, 12:34,2 users,load average: 0.04, 0.11, 0.13 Tasks: 197 total,1 running, 192 sleeping,4 stopped,0 zombie %Cpu0:2.0 us,0.3 sy,0.0 ni, 97.7 id,0.0 wa,0.0 hi,0.0 si,0.0 st %Cpu1:1.7 us,0.3 sy,0.0 ni, 98.0 id,0.0 wa,0.0 hi,0.0 si,0.0 st %Cpu2:1.0 us,0.3 sy,0.0 ni, 98.7 id,0.0 wa,0.0 hi,0.0 si,0.0 st %Cpu3:2.0 us,0.7 sy,0.0 ni, 97.3 id,0.0 wa,0.0 hi,0.0 si,0.0 st KiB Mem : 16266636 total,1208312 free,5560320 used,9498004 buff/cache KiB Swap:8388604 total,8388604 free,0 used.9973728 avail Mem

nginx配置CPU亲和:
[root@zq]# cat /etc/nginx/nginx.conf user nginx; worker_processes4; #与cpu数一致##方法1,当CPU核心数多时,就不好些了,建议采用方法2 #worker_cpu_affinity 0001 0010 0100 1000; #cpu数4个,所以4位,1在第几位表示使用第几个cpu核心##方法2 worker_cpu_affinity auto; error_log/var/log/nginx/error.log warn; pid/var/run/nginx.pid; #worker_rlimit_nofile 65535; #nginx进程文件句柄限制events { worker_connections1024; }

样例:
nginx未配置CPU亲和,查看nginx进程使用CPU情况:
[root@zq]# ps -eo pid,args,psr | grep nginx#psr指使用的哪一个cpu 9472 cat /var/log/nginx/access.l2 9483 tail -f /var/log/nginx/acce3 20824 grep --color=auto nginx1 27638 nginx: worker process0 27639 nginx: worker process0 27640 nginx: worker process3 27641 nginx: worker process3 30316 nginx: master process /usr/1

修改nginx.conf,增加worker_cpu_affinity 0001 0010 0100 1000; ,重加载nginx载查看nginx进程均匀的使用4个CPU核心:
[root@zq]# vi /etc/nginx/nginx.conf [root@zq]# nginx -s reload -c /etc/nginx/nginx.conf nginx: [warn] conflicting server name "127.0.0.1" on 0.0.0.0:443, ignored nginx: [warn] conflicting server name "127.0.0.1" on 0.0.0.0:443, ignored [root@zq]# ps -eo pid,args,psr | grep nginx 9472 cat /var/log/nginx/access.l2 9483 tail -f /var/log/nginx/acce3 21080 nginx: worker process0 21081 nginx: worker process1 21082 nginx: worker process2 21083 nginx: worker process3 21090 grep --color=auto nginx1 30316 nginx: master process /usr/0


    推荐阅读