关于nginx性能优化CPU参数worker_cpu_affinity

时间:2021-11-15 06:00:20

Nginx性能优化CPU参数worker_cpu_affinity使用说明


官方说明:http://wiki.nginx.org/NginxHttpMainModule#worker_cpu_affinit引用worker_cpu_affinity
Syntax: worker_cpu_affinity cpumask [cpumask...]

Default: none

Linux only.

With this option you can bind the worker process to a CPU, it calls sched_setaffinity().

For example,

worker_processes     4;
worker_cpu_affinity 0001 0010 0100 1000;
Bind each worker process to one CPU only.

worker_processes     2;
worker_cpu_affinity 0101 1010;
Bind the first worker to CPU0/CPU2, bind the second worker to CPU1/CPU3. This is suitable for HTT.



一个服务器为Q9300单cpu,4核心,于是可以直接用官方的配置:worker_cpu_affinity 0001 0010 0100 1000;
效果如下,看起来每个cpu核心都比较平均:

top - 21:17:56 up 4 days,  7:41,  3 users,  load average: 0.25, 0.44, 0.47
Tasks: 238 total,   1 running, 237 sleeping,   0 stopped,   0 zombie
Cpu0  :  0.3%us,  0.3%sy,  0.0%ni, 94.2%id,  5.2%wa,  0.0%hi,  0.0%si,  0.0%st
Cpu1  :  0.3%us,  0.0%sy,  0.0%ni, 96.2%id,  0.6%wa,  0.6%hi,  2.2%si,  0.0%st
Cpu2  :  0.3%us,  0.0%sy,  0.0%ni, 93.5%id,  5.5%wa,  0.0%hi,  0.6%si,  0.0%st
Cpu3  :  0.0%us,  0.0%sy,  0.0%ni, 96.5%id,  3.5%wa,  0.0%hi,  0.0%si,  0.0%st
Mem:   8119372k total,  3641940k used,  4477432k free,   504900k buffers

Swap:  8385888k total,    10664k used,  8375224k free,  2407512k cached

本站所在VPS的CPU为Intel(R) Xeon(R) CPU E5520 @ 2.27GHz x 2,因此写为:

worker_processes     2;
worker_cpu_affinity 01 10;


若要2核CPU开4进程,那么可以写为:

worker_processes     4;
worker_cpu_affinity 01 10 01 10;


2核是 01,四核是0001,8核是00000001,有多少个核,就有几位数,1表示该内核开启,0表示该内核关闭。
worker_processes最多开启8个,8个以上性能提升不会再提升了,而且稳定性变得更低,所以8个进程够用了。