1 // Copyright 2016 Google Inc. All rights reserved
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "affinity.h"
16 
17 #include "flags.h"
18 #include "log.h"
19 
20 #ifdef __linux__
21 
22 #include <sched.h>
23 
SetAffinityForSingleThread()24 void SetAffinityForSingleThread() {
25   cpu_set_t cs;
26   CPU_ZERO(&cs);
27   int n = g_flags.num_cpus / 2;
28   CPU_SET(n, &cs);
29   if (n > 1)
30     CPU_SET(n + 1, &cs);
31   if (sched_setaffinity(0, sizeof(cs), &cs) < 0)
32     WARN("sched_setaffinity: %s", strerror(errno));
33 }
34 
SetAffinityForMultiThread()35 void SetAffinityForMultiThread() {
36   cpu_set_t cs;
37   CPU_ZERO(&cs);
38   for (int i = 0; i < g_flags.num_cpus; i++) {
39     CPU_SET(i, &cs);
40   }
41   if (sched_setaffinity(0, sizeof(cs), &cs) < 0)
42     WARN("sched_setaffinity: %s", strerror(errno));
43 }
44 
45 #else
46 
SetAffinityForSingleThread()47 void SetAffinityForSingleThread() {}
SetAffinityForMultiThread()48 void SetAffinityForMultiThread() {}
49 
50 #endif
51