使用C语言设置CPU亲和度

一台计算机上可能有多个CPU,如何让程序只在特定的CPU上运行呢?

设置CPU亲和度的API位于头文件<sched.h>中:

1
vim /usr/include/sched.h

CPU亲和度

1
2
3
4
5
6
7
#define _GNU_SOURCE

gcc -D_GNU_SOURCE xx.c

or

#define __USE_GNU
1
2
3
4
5
6
7
8
9
#include <sched.h>

static int setaffinity(int c)
{
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(c, &cpuset);
return sched_setaffinity(0, sizeof(cpuset), &cpuset);
}

测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <fcntl.h>
#include <unistd.h>
#include <sched.h>

static int setaffinity(int c)
{
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(c, &cpuset);
return sched_setaffinity(0, sizeof(cpuset), &cpuset);
}

static void set_test_root(int id, char *test_root)
{
sprintf(test_root, "%s/%d", fx_opt->root, worker->id);
}

static int pre_work(struct worker *worker)
{
char test_root[PATH_MAX];
set_test_root(worker, test_root);
return mkdir_p(test_root);
}

static int main_work(struct worker *worker)
{
char test_root[PATH_MAX];
struct bench *bench = worker->bench;
uint64_t iter;
int rc = 0;

set_test_root(worker, test_root);
for (iter = 0; !stop; ++iter) {
char file[PATH_MAX];
int fd;
/* create and close */
snprintf(file, PATH_MAX, "%s/n_inode_alloc-%" PRIu64 ".dat",
test_root, iter);
if ((fd = open(file, O_CREAT | O_RDWR, S_IRWXU)) == -1)
goto err_out;
close(fd);
}
out:
worker->works = (double)iter;
return rc;
err_out:
stop = 1;
rc = errno;
goto out;
}

----------本文结束感谢您的阅读----------
坚持原创技术分享,您的支持将鼓励我继续创作!