意义
Nginx默认没有开启利用多核cpu,我们可以通过worker_processes
指令来启动多个worker,但是worker最终运行在哪些cpu核上是系统层进行调度的;我们可以通过增加worker_cpu_affinity
指令来对worker所运行的cpu核做绑定,以此充分利用cpu多核cpu的性能。cpu是任务处理、计算最关键的资源,cpu核越多,性能就越好;通过将nginx worker绑定到特定的CPU上可以避免因为worker被频繁调度带来的CPU的cache miss和某些cpu核负载不均的问题。
配置方式
官方文档: http://nginx.org/en/docs/ngx_core_module.html#worker_cpu_affinity
配置方式1 手动绑定
需要手动写要绑定到CPU核的配置,cpu有多少个核,就有几位数,1代表内核开启,0代表内核关闭
eg: 启动4个worker,分别绑定到CPU0~CPU3上
worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000;
or
启动2个worker;worker 1 绑定到CPU0/CPU2上;worker 2 绑定到CPU1/CPU3上
worker_processes 2;
worker_cpu_affinity 0101 1010;
配置方式2 自动绑定(建议方式)
eg: 自适应的方式来启动一定数量的worker,并且自动绑定到对应的cpu核心上,这里启动的worker数量和cpu核心数相同;
The special value auto (1.9.10) allows binding worker processes automatically to available CPUs
worker_processes auto;
worker_cpu_affinity auto;
也可以通过下面的配置方式来限制CPU资源的使用,只将nginx worker绑定到特定的一些cpu核心上:
worker_cpu_affinity auto 01010101;
调整前
通过统计nginx进程运行所在的cpu核心,可以看到某些核心上有多个nginx worker进程;并且在cpu核心和线程数量的关系是变化的,这里就说明nginx的worker进程是在cpu核心之间是动态调度的;因此这种场景下发生cpu cache miss的概率就会高很多(相比不动态调度)。
# 第一次检查
[root@thatsit conf]# ps -eo pid,ni,pri,pcpu,psr,comm|grep nginx|awk '{++s[$(NF-1)]}END{for (i in s)print "core-id",i," ",s[i]}'|sort -nr -k 3
core-id 20 6
core-id 22 5
core-id 5 4
core-id 3 4
core-id 0 4
core-id 25 3
core-id 2 3
core-id 7 2
core-id 4 2
core-id 27 2
core-id 24 2
core-id 6 1
core-id 26 1
core-id 11 1
core-id 1 1
[root@thatsit nginx]#
# 第二次检查
[root@thatsit conf]# ps -eo pid,ni,pri,pcpu,psr,comm|grep nginx|awk '{++s[$(NF-1)]}END{for (i in s)print "core-id",i," ",s[i]}'|sort -nr -k 3
core-id 4 6
core-id 0 6
core-id 1 5
core-id 7 4
core-id 3 4
core-id 6 3
core-id 5 2
core-id 27 2
core-id 24 2
core-id 23 2
core-id 26 1
core-id 25 1
core-id 21 1
core-id 20 1
core-id 11 1
[root@thatsit conf]#
PS:两次检查操作的时间间隔非常短,在几秒之内;
配置Nginx CPU亲和性
之前Nginx的worker数量是auto的(worker_processes auto;
),但是没有配置worker_cpu_affinity
;添加下这个配置;
> worker_cpu_affinity auto;
调整后确认
调整之后所有Nginx的Worker都会跟每一个逻辑核绑定,一个worker只会运行在一个核心上。下面统计中core-id 11
上有2个nginx进程的原因是:其中一个是nginx的master进程。
[root@thatsit conf]# ps -eo pid,ni,pri,pcpu,psr,comm|grep nginx|awk '{++s[$(NF-1)]}END{for (i in s)print "core-id",i," ",s[i]}'|sort -nr -k 3
core-id 11 2
core-id 9 1
core-id 8 1
core-id 7 1
core-id 6 1
core-id 5 1
core-id 4 1
core-id 39 1
core-id 38 1
core-id 37 1
core-id 36 1
core-id 35 1
core-id 34 1
core-id 33 1
core-id 32 1
core-id 31 1
core-id 3 1
core-id 30 1
core-id 29 1
core-id 28 1
core-id 27 1
core-id 26 1
core-id 25 1
core-id 24 1
core-id 23 1
core-id 22 1
core-id 21 1
core-id 2 1
core-id 20 1
core-id 19 1
core-id 18 1
core-id 17 1
core-id 16 1
core-id 15 1
core-id 14 1
core-id 13 1
core-id 12 1
core-id 1 1
core-id 10 1
core-id 0 1
[root@thatsit conf]#