1+ #include " CpuUtils.h"
2+ #include < cstdio>
3+
4+ std::vector<std::size_t > getThreadAffinity () {
5+ std::vector<std::size_t > cores;
6+ pthread_t self = pthread_self ();
7+ cpu_set_t cpuset;
8+ CPU_ZERO (&cpuset);
9+ ::pthread_getaffinity_np (self, sizeof (cpuset), &cpuset);
10+ for (int j = 0 ; j < CPU_SETSIZE ; j++) {
11+ if (CPU_ISSET (j, &cpuset)) {
12+ cores.push_back (j);
13+ }
14+ }
15+ return cores;
16+ }
17+
18+ bool setThreadAfinity (const std::vector<std::size_t >& cores) {
19+ pthread_t self = pthread_self ();
20+ cpu_set_t mask;
21+ CPU_ZERO (&mask);
22+ for (std::size_t core : cores) {
23+ CPU_SET (core, &mask);
24+ }
25+ int err = ::pthread_setaffinity_np (self, sizeof (mask), &mask);
26+ return (err == 0 );
27+ }
28+
29+ bool setThreadAfinity (std::size_t core) {
30+ pthread_t self = pthread_self ();
31+ cpu_set_t mask;
32+ CPU_ZERO (&mask);
33+ CPU_SET (core, &mask);
34+ int err = ::pthread_setaffinity_np (self, sizeof (mask), &mask);
35+ return (err == 0 );
36+ }
37+
38+ std::size_t getCurrentCore () {
39+ return sched_getcpu ();
40+ }
41+
42+ std::size_t getNumberOfCores () {
43+ return get_nprocs_conf ();
44+ }
45+
46+ const char * getPolicyName (int policy) {
47+ switch (policy) {
48+ case SCHED_RR : return " RoundRobin" ; break ;
49+ case SCHED_BATCH : return " Batch" ; break ;
50+ case SCHED_OTHER : return " Standard" ; break ;
51+ case SCHED_IDLE : return " Idle" ; break ;
52+ default : return " N/A" ; break ;
53+ }
54+ }
55+
56+ bool setPriority (int scheduler, int prio) {
57+ pthread_t tid = pthread_self ();
58+ struct sched_param param;
59+ int policy;
60+ int res = pthread_getschedparam (tid, &policy, ¶m);
61+ if (res != 0 ) {
62+ perror (" pthread_getschedparam" );
63+ return false ;
64+ }
65+ param.sched_priority = prio;
66+ res = pthread_setschedparam (tid, scheduler, ¶m);
67+ if (res != 0 ) {
68+ perror (" pthread_setschedparam" );
69+ return false ;
70+ }
71+ return true ;
72+ }
73+
74+ void setRealtimePriority (int prio) {
75+ setPriority (SCHED_RR , prio);
76+ }
77+
78+ void setIdlePriority (int prio) {
79+ setPriority (SCHED_IDLE , prio);
80+ }
81+
82+ void setStandardPriority (int prio) {
83+ setPriority (SCHED_OTHER , prio);
84+ }
0 commit comments