CPU Affinity (CPU亲合力)

来源:互联网 发布:淘宝助理怎么管理订单 编辑:程序博客网 时间:2024/05/01 02:13

CPU亲合力就是指在Linux系统中能够将一个或多个进程绑定到一个或多个处理器上运行。

一个进程的CPU亲合力掩码决定了该进程将在哪个或哪几个CPU上运行。在一个多处理器系统中,设置CPU亲合力的掩码可能会获得更好的性能。

一个CPU的亲合力掩码用一个cpu_set_t结构体来表示一个CPU集合,下面的几个宏分别对这个掩码集进行操作:

  • CPU_ZERO() 清空一个集合
  • CPU_SET()与CPU_CLR()分别对将一个给定的CPU号加到一个集合或者从一个集合中去掉。
  • CPU_ISSET()检查一个CPU号是否在这个集合中。

下面两个函数就是用来设置获取线程CPU亲和力状态:

sched_setaffinity(pid_t pid, unsigned int cpusetsize, cpu_set_t mask)

该函数设置进程为pid的这个进程,让它运行在mask所设定的CPU上。如果pid的值为0,则表示指定的是当前进程,使当前进程运行在mask所设定的那些CPU上。第二个参数cpusetsize是mask所指定的数的长度,通常设定为sizeof(cpu_set_t)。如果当前pid所指定的进程此时没有运行在mask所指定的任意一个CPU上,则该指定的进程会从其它CPU上迁移到mask的指定的一个CPU上运行。

sched_getaffinity(pid_t pid, unsigned int cpusetsize, cpu_set_t *mask)

该函数获得pid所指示的进程的CPU位掩码,并将该掩码返回到mask所指向的结构中,即获得指定pid当前可以运行在哪些CPU上。同样,如果pid的值为0,也表示的是当前进程。

Name

sched_setaffinity, sched_getaffinity - set and get a process’s CPU affinity mask

Synopsis

#define _GNU_SOURCE    /* See feature_test_macros(7) */#include <sched.h>
int sched_setaffinity(pid_t pid, size_t cpusetsize,                      cpu_set_t *mask);int sched_getaffinity(pid_t pid, size_t cpusetsize,                      cpu_set_t *mask);

Description

A process’s CPU affinity mask determines the set of CPUs on which it is eligible to run. On a multiprocessor system, setting the CPU affinity mask can be used to obtain performance benefits. For example, by dedicating one CPU to a particular process (i.e., setting the affinity mask of that process to specify a single CPU, and setting the affinity mask of all other processes to exclude that CPU), it is possible to ensure maximum execution speed for that process. Restricting a process to run on a single CPU also avoids the performance cost caused by the cache invalidation that occurs when a process ceases to execute on one CPU and then recommences execution on a different CPU.

A CPU affinity mask is represented by the cpu_set_t structure, a “CPU set”, pointed to by mask. A set of macros for manipulating CPU sets is described in cpu_set(3).

sched_setaffinity() sets the CPU affinity mask of the process whose ID is pid to the value specified by mask. If pid is zero, then the calling process is used. The argument cpusetsize is the length (in bytes) of the data pointed to by mask. Normally this argument would be specified as sizeof(cpu_set_t).
If the process specified by pid is not currently running on one of the CPUs specified in mask, then that process is migrated to one of the CPUs specified in mask.

sched_getaffinity() writes the affinity mask of the process whose ID is pid into the cpu_set_t structure pointed to by mask. The cpusetsize argument specifies the size (in bytes) of mask. If pid is zero, then the mask of the calling process is returned.

Return Value

On success, sched_setaffinity() and sched_getaffinity() return 0. On error, -1 is returned, and errno is set appropriately.

Errors

EFAULT
A supplied memory address was invalid.

EINVAL
The affinity bit mask mask contains no processors that are currently physically on the system and permitted to the process according to any restrictions that may be imposed by the “cpuset” mechanism described in cpuset(7).

EINVAL
(sched_getaffinity() and, in kernels before 2.6.9, sched_setaffinity()) cpusetsize is smaller than the size of the affinity mask used by the kernel.

EPERM
(sched_setaffinity()) The calling process does not have appropriate privileges. The caller needs an effective user ID equal to the real user ID or effective user ID of the process identified by pid, or it must possess the CAP_SYS_NICE capability.

ESRCH
The process whose ID is pid could not be found.

/*** Auth: Yangsc** Date: 2016.03.16*/#include <stdio.h>#define __USE_GNU  #include <sys/syscall.h>#include <sys/time.h>#include <unistd.h>#include <errno.h>#include <sched.h>#define CAT_MAX_VALUE   1000000000#define DOG_MAX_VALUE   4000000000#define MSECOND         1000000typedef struct{    unsigned long long cat;    unsigned long long dog;}pets_t;int main( int argc, char* argv[] ){    pets_t pets;    unsigned long long cnt = 0;    struct timeval tpstart, tpend;    float timeuse;    int cpu_id;    int cpu_cnt = sysconf(_SC_NPROCESSORS_CONF);    if(argc != 2)    {        printf("usage:./affinity num\n");        return -1;    }    cpu_id = atoi(argv[1]);    if(cpu_id > cpu_cnt)    {        printf("%d is large than cpu count:%d\n", cpu_id, cpu_cnt);        return -1;    }    printf("set affinity cpu id:%d, total cpus:%d\n", cpu_id, cpu_cnt);    pets.cat = 0;    pets.dog = 0;    cpu_set_t mask;    CPU_ZERO(&mask);    CPU_SET(cpu_id, &mask);    if(sched_setaffinity(0, sizeof(cpu_set_t), &mask) != 0)    {        printf("setup cpu affinity fail:%s\n", strerror(errno));        return -1;    }    gettimeofday(&tpstart, NULL);    for(cnt = 0; cnt < CAT_MAX_VALUE; cnt++)    {        pets.cat += cnt;    }    for(cnt = 0; cnt < DOG_MAX_VALUE; cnt++)    {        pets.dog += cnt;    }    /*get start time*/    gettimeofday(&tpend, NULL);    /*calculate time*/    timeuse = MSECOND * (tpend.tv_sec-tpstart.tv_sec) + tpend.tv_usec - tpstart.tv_usec;    timeuse /= MSECOND;    printf("Used Time:%f\n", timeuse);    CPU_ZERO(&mask);    if(sched_getaffinity(0, sizeof(cpu_set_t), &mask) != 0)    {        printf("get cpu affinity fail:%s\n", strerror(errno));        return -1;    }    for(cpu_id = 0; cpu_id < cpu_cnt; cpu_id++)    {        if(CPU_ISSET(cpu_id, &mask))        {            printf("tid %d is running on cpu %d\n",(int)syscall(SYS_gettid), cpu_id);        }    }    return 0;}

以上代码在CentOS6上验证通过。
系统信息

执行:
执行结果

查看CPU占用率:
CPU占用率

0 0