1 /** 2 * Copyright 2021 Huawei Technologies Co., Ltd 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef MINDSPORE_CORE_MINDRT_RUNTIME_CORE_AFFINITY_H_ 18 #define MINDSPORE_CORE_MINDRT_RUNTIME_CORE_AFFINITY_H_ 19 20 #include <vector> 21 #include <thread> 22 23 #ifdef __ANDROID__ 24 #define BIND_CORE 25 #include <sched.h> 26 #endif 27 28 namespace mindspore { 29 enum BindMode { 30 Power_NoBind = 0, // free schedule 31 Power_Higher = 1, 32 Power_Middle = 2, 33 }; 34 35 class Worker; 36 class CoreAffinity { 37 public: 38 CoreAffinity() = default; 39 ~CoreAffinity() = default; 40 41 int InitHardwareCoreInfo(); 42 43 int BindThreads(const std::vector<Worker *> &workers, const std::vector<int> &core_list); 44 int BindThreads(const std::vector<Worker *> &workers, BindMode bind_mode); 45 int BindProcess(BindMode bind_mode) const; 46 std::vector<int> GetCoreId(size_t thread_num, BindMode bind_mode); 47 void SetCoreId(const std::vector<int> &core_list); 48 49 private: 50 #ifdef BIND_CORE 51 int SetAffinity(const pthread_t &thread_id, cpu_set_t *cpu_set) const; 52 #endif // BIND_CORE 53 54 int InitBindCoreId(size_t thread_num, BindMode bind_mode); 55 56 int BindThreadsToCoreList(const std::vector<Worker *> &workers) const; 57 int FreeScheduleThreads(const std::vector<Worker *> &workers) const; 58 59 // bind_id contains the CPU cores to bind 60 // the size of bind_id is equal to the size of workers 61 std::vector<int> bind_id_; 62 // sorted_id contains the ordered CPU core id 63 // the size of sorted_id is equal to the size of hardware_concurrency 64 std::vector<int> sorted_id_; 65 // used to store the frequency of core 66 // the core id corresponds to the index 67 std::vector<int> core_freq_; 68 size_t core_num_{0}; 69 size_t higher_num_{0}; 70 }; 71 72 } // namespace mindspore 73 74 #endif // MINDSPORE_CORE_MINDRT_RUNTIME_CORE_AFFINITY_H_ 75