1 /* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 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 16 #ifndef JS_CONCURRENT_MODULE_COMMON_HELPER_CONCURRENT_HELPER_H 17 #define JS_CONCURRENT_MODULE_COMMON_HELPER_CONCURRENT_HELPER_H 18 19 #include <chrono> 20 #if defined(OHOS_PLATFORM) 21 #include <unistd.h> 22 #elif defined(WINDOWS_PLATFORM) 23 #include <windows.h> 24 #elif defined(MAC_PLATFORM) || defined(IOS_PLATFORM) 25 #include <sys/sysctl.h> 26 #elif defined(ANDROID_PLATFORM) 27 #include <sys/sysinfo.h> 28 #endif 29 30 #if __GNUC__ 31 #define LIKELY(x) __builtin_expect(!!(x), 1) 32 #define UNLIKELY(x) __builtin_expect(!!(x), 0) 33 #else 34 #define LIKELY(x) (!!(x)) 35 #define UNLIKELY(x) (!!(x)) 36 #endif // __GNUC__ 37 38 namespace Commonlibrary::Concurrent::Common::Helper { 39 class ConcurrentHelper { 40 public: 41 ConcurrentHelper() = delete; 42 ~ConcurrentHelper() = delete; 43 GetActiveCpus()44 static uint32_t GetActiveCpus() 45 { 46 #if defined(OHOS_PLATFORM) 47 return sysconf(_SC_NPROCESSORS_ONLN); 48 #elif defined(WINDOWS_PLATFORM) 49 SYSTEM_INFO sysInfo; 50 GetSystemInfo(&sysInfo); 51 return sysInfo.dwNumberOfProcessors; 52 #elif defined(MAC_PLATFORM) || defined(IOS_PLATFORM) 53 int32_t numCpu = 0; 54 size_t size = sizeof(numCpu); 55 sysctlbyname("hw.ncpu", &numCpu, &size, nullptr, 0); 56 return numCpu; 57 #elif defined(ANDROID_PLATFORM) 58 return get_nprocs(); 59 #else 60 return 1; // 1: default number 61 #endif 62 } 63 GetMilliseconds()64 static uint64_t GetMilliseconds() 65 { 66 auto now = std::chrono::system_clock::now(); 67 auto millisecs = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()); 68 return millisecs.count(); 69 } 70 }; 71 } // namespace Commonlibrary::Concurrent::Common::Helper 72 #endif // JS_CONCURRENT_MODULE_COMMON_HELPER_CONCURRENT_HELPER_H