linux下指定进程运行的CPU

如果你觉得比内核的进程调度器更了解你的进程,不想过多的占用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 
版权声明:本文为博主原创文章,转载请附上博文链接!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值