在閱讀Nginx模塊開發與架構模式一書時:nginx
"Nginx 上的進程數 與CPU核心數相等時(最好每一個worker進程都綁定特定的CPU核心),進程間切換的代價是最小的;" && "咱們不能任由操做系統負載均衡,由於咱們本身更瞭解本身的程序,因此,咱們能夠手動地爲其分配CPU核,而不會過多地佔用CPU0,或是讓咱們關鍵進程和一堆別的進程擠在一塊兒"ubuntu
引伸出此文:架構
綁定CPU核心:oracle
1.taskset負載均衡
taskset是LINUX提供的一個命令(ubuntu系統可能須要自行安裝,schedutils package)。他能夠讓某個程序運行在某個(或)某些CPU上。spa
如下均以Nginx舉例。操作系統
1)顯示進程運行的CPU3d
命令code
[oracle@oracle ~]$ taskset -p 1765
pid 1765's current affinity mask: 3 --- 轉化爲 2進制 11blog
// 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運行狀態;