1// Copyright 2023 The Chromium Authors 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5#include "base/system/sys_info.h" 6 7#include <sys/sysctl.h> 8 9#include "base/strings/stringprintf.h" 10#include "base/system/sys_info_internal.h" 11 12namespace base { 13 14namespace internal { 15 16// Queries sysctlbyname() for the given key and returns the 32 bit integer value 17// from the system or std::nullopt on failure. 18// https://github.com/apple/darwin-xnu/blob/2ff845c2e033bd0ff64b5b6aa6063a1f8f65aa32/bsd/sys/sysctl.h#L1224-L1225 19std::optional<int> GetSysctlIntValue(const char* key_name) { 20 int value; 21 size_t len = sizeof(value); 22 if (sysctlbyname(key_name, &value, &len, nullptr, 0) != 0) { 23 return std::nullopt; 24 } 25 DCHECK_EQ(len, sizeof(value)); 26 return value; 27} 28 29} // namespace internal 30 31// static 32int SysInfo::NumberOfEfficientProcessorsImpl() { 33 int num_perf_levels = 34 internal::GetSysctlIntValue("hw.nperflevels").value_or(1); 35 if (num_perf_levels == 1) { 36 return 0; 37 } 38 DCHECK_GE(num_perf_levels, 2); 39 40 // Lower values of perflevel indicate higher-performance core types. See 41 // https://developer.apple.com/documentation/kernel/1387446-sysctlbyname/determining_system_capabilities?changes=l__5 42 int num_of_efficient_processors = 43 internal::GetSysctlIntValue( 44 StringPrintf("hw.perflevel%d.logicalcpu", num_perf_levels - 1) 45 .c_str()) 46 .value_or(0); 47 DCHECK_GE(num_of_efficient_processors, 0); 48 49 return num_of_efficient_processors; 50} 51 52} // namespace base 53