cpu亲和性测试

发布时间 2023-12-19 16:04:05作者: OzTaking
CmakeList.txt 
1 cmake_minimum_required(VERSION 3.25)
2 project(_01_pthread_setaffinity C)
3 
4 set(CMAKE_C_STANDARD 11)
5 
6 add_executable(_01_pthread_setaffinity main.c)
7 
8 target_link_libraries(${PROJECT_NAME} pthread)

main

 1 #define _GNU_SOURCE
 2 #include <pthread.h>
 3 #include <stdio.h>
 4 #include <stdlib.h>
 5 #include <errno.h>
 6 
 7 #define handle_error_en(en, msg) \
 8                do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
 9 
10 
11 int main() {
12     int s, j;
13     cpu_set_t cpuset;
14     pthread_t thread;
15 
16     thread = pthread_self();
17 
18     /* Set affinity mask to include CPUs 0 to 7 */
19 
20     CPU_ZERO(&cpuset);
21     for (j = 0; j < 8; j++)
22         CPU_SET(j, &cpuset);
23 
24     s = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
25     if (s != 0)
26         handle_error_en(s, "pthread_setaffinity_np");
27 
28     /* Check the actual affinity mask assigned to the thread */
29 
30     s = pthread_getaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
31     if (s != 0)
32         handle_error_en(s, "pthread_getaffinity_np");
33 
34     printf("Set returned by pthread_getaffinity_np() contained:\n");
35     for (j = 0; j < CPU_SETSIZE; j++)
36         if (CPU_ISSET(j, &cpuset))
37             printf("    CPU %d\n", j);
38 
39     exit(EXIT_SUCCESS);
40 //    return 0;
41 }

参考文章:

https://blog.csdn.net/arnoldlu/article/details/52876256