如果你覺得比內核的進程調度器更瞭解你的進程,不想過多的佔用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 // 注意,下面的方法,有可能有問題,__USE_GNU 應該不能這麼用。
// 另一個文章裏已經說明。 在此僅爲轉述。
#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;
}
---------------------
作者:老豬jim
來源:CSDN
原文:https://blog.csdn.net/zj_jim/article/details/50930182
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!