Nginx 关于进程数 与CPU核心数相等时,进程间切换的代价是最小的-- 绑定CPU核心

在阅读Nginx模块开发与架构模式一书时:

  "Nginx  上的进程数 与CPU核心数相等时(最好每个worker进程都绑定特定的CPU核心),进程间切换的代价是最小的;"  &&  "我们不能任由操作系统负载均衡,因为我们自己更了解自己的程序,所以,我们可以手动地为其分配CPU核,而不会过多地占用CPU0,或是让我们关键进程和一堆别的进程挤在一起"

  引申出此文:

     绑定CPU核心:


1.taskset

  taskset是LINUX提供的一个命令(ubuntu系统可能需要自行安装,schedutils package)。他可以让某个程序运行在某个(或)某些CPU上。

以下均以Nginx举例。

1)显示进程运行的CPU

命令

[oracle@oracle ~]$ taskset -p 1765
pid 1765's current affinity mask: 3     --- 转化为 2进制  11

// 1765 是oracle 进程

显示结果的3实际上是二进制3个低位均为1的bitmask,每一个1对应于1个CPU,表示该进程在2个CPU上运行

 

2)指定进程运行在某个特定的CPU上

[root@oracle ~]# taskset -pc 0 1765
pid 1765's current affinity list: 0,1    --- 当前系统 cpu core
pid 1765's new affinity list: 0

//注:0表示CPU将只会运行在第1个CPU上(从0开始计数)。

3)进程启动时指定CPU

命令

 taskset -c 0  /usr/sbin/nginx -c /etc/nginx/nginx.conf

 

 

 

2.sched_setaffinity系统调用#include <stdio.h>

#include <math.h>   // -lm
#include <sched.h>
 
double waste_time(long n)
{
    double res = 0;
    long double i = 0;
    for(i=0; i <n * 200000; i++)
     res += sqrt(i); return res; } int main(int argc, char **argv) { unsigned long mask = 1; /* processor 0 */ /* bind process to processor 0 */ if (sched_setaffinity(0, sizeof(mask), &mask) <0) { // int sched_setaffinity(pid_t pid, size_t cpusetsize, cpu_set_t *mask); perror("sched_setaffinity error\n"); } /* waste some time so the work is visible with "top" */ printf ("result: %f\n", waste_time (200000)); mask = 2; /* process switches to processor 1 now */ if (sched_setaffinity(0, sizeof(mask), &mask) <0) { perror("sched_setaffinity error\n"); } /* waste some more time to see the processor switch */ printf ("result: %f\n", waste_time (20000)); }

 

  运行时 进入 top  然后摁 1 即可看到每个CPU运行状态;

            

         

 

posted @ 2017-04-26 16:44  Rocky_Ansi  阅读(1209)  评论(0编辑  收藏  举报