• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright 2019 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 #ifndef MINDSPORE_CORE_UTILS_MS_UTILS_H_
17 #define MINDSPORE_CORE_UTILS_MS_UTILS_H_
18 
19 #include <memory>
20 #include <utility>
21 #include <string>
22 #include <vector>
23 #include <atomic>
24 #include <thread>
25 
26 #define DISABLE_COPY_AND_ASSIGN(ClassType) \
27   ClassType(const ClassType &) = delete;   \
28   ClassType &operator=(const ClassType &) = delete;
29 
30 namespace mindspore {
31 namespace common {
SafeCStr(const std::string & str)32 inline const char *SafeCStr(const std::string &str) { return str.c_str(); }
33 const char *SafeCStr(const std::string &&str);
34 
GetEnv(const std::string & envvar)35 static inline std::string GetEnv(const std::string &envvar) {
36   const char *value = ::getenv(envvar.c_str());
37 
38   if (value == nullptr) {
39     return std::string();
40   }
41 
42   return std::string(value);
43 }
44 
45 static inline int SetEnv(const char *envname, const char *envvar, int overwrite = 1) {
46 #if defined(_WIN32)
47   return 0;
48 #else
49   return ::setenv(envname, envvar, overwrite);
50 #endif
51 }
52 
SetOMPThreadNum()53 static inline void SetOMPThreadNum() {
54   size_t cpu_core_num = std::thread::hardware_concurrency();
55   size_t cpu_core_num_half = cpu_core_num / 2;
56   const size_t kOMPThreadMaxNum = 16;
57   const size_t kOMPThreadMinNum = 1;
58 
59   size_t OMP_thread_num = cpu_core_num_half < kOMPThreadMinNum ? kOMPThreadMinNum : cpu_core_num_half;
60   OMP_thread_num = OMP_thread_num > kOMPThreadMaxNum ? kOMPThreadMaxNum : OMP_thread_num;
61 
62   std::string OMP_env = std::to_string(OMP_thread_num);
63   (void)SetEnv("OMP_NUM_THREADS", OMP_env.c_str(), 0);
64 }
65 }  // namespace common
66 }  // namespace mindspore
67 
68 #endif  // MINDSPORE_CORE_UTILS_MS_UTILS_H_
69