如果你覺得比核心的進程調度器更瞭解你的進程,不想過多的佔用CPU0,更高的快取命中,那麼可以設定進程運行在某個或某些CPU上。
redis是單進程模型,為了充分利用多核伺服器效能,可以指定不同的redis執行個體運行在不同CPU上,這樣也可以減少進程環境切換。
方法有兩種:
一、使用命令taskset
在RedHat系linux中,可以sudo yum privodes taskset尋找taskset在哪個包中,如下所示:
util-linux-2.23.2-26.el7.x86_64 : A collection of basic system utilities
Repo : @anaconda
Matched from:
Filename : /usr/bin/taskset
可以知道是在util-linux-2.23.2-26.el7.x86_64,那麼sudo yum install util-linux就可以裝上。
a.顯示進程運行在哪些CPU上
[zhujiang@localhost ~]$ ps aux | grep redis
root 2884 0.1 0.2 37260 5372 ? Ssl Mar10 3:53 /usr/local/bin/redis-server *:6379
zhujiang 17266 0.0 0.0 112648 956 pts/0 S+ 05:57 0:00 grep --color=auto redis
[zhujiang@localhost ~]$ taskset -p 2884
pid 2884's current affinity mask: f
顯示結果f表示二進位的1111,每一個1表示一個CPU,說明這個進程運行在4個CPU上,我這台虛擬機器正是四個CPU。
b.指定進程運行在某CPU上
[zhujiang@localhost ~]$ sudo taskset -pc 2 2884
pid 2884's current affinity list: 0-3
pid 2884's new affinity list: 2
[zhujiang@localhost ~]$
註:2表示該進程只會運行在第3個CPU上(從0開始計數)
c.進程啟動時指定CPU
[zhujiang@localhost ~]$ taskset -c 0 /usr/local/bin/redis-server
二、使用sched_setaffinity
#include <stdio.h>#include <time.h>#include <stdlib.h>#define __USE_GNU#include <sched.h>int main(){ int cpu_id = 1; cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(cpu_id, &mask); if (sched_setaffinity(0, sizeof(mask), &mask) < 0) { perror("set affinity"); return -1; } struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); int now = ts.tv_sec; int end = now + 20; //忙計算10秒 while (now < end) { clock_gettime(CLOCK_MONOTONIC, &ts); now = ts.tv_sec; } CPU_ZERO(&mask); cpu_id = 3; CPU_SET(cpu_id, &mask); if (sched_setaffinity(0, sizeof(mask), &mask) < 0) { perror("set affinity"); return -1; } clock_gettime(CLOCK_MONOTONIC, &ts); now = ts.tv_sec; end = now + 10; while (now < end) { clock_gettime(CLOCK_MONOTONIC, &ts); now = ts.tv_sec; } return 0;}