chromium/base/power_monitor/cpu_frequency_utils.cc

// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/power_monitor/cpu_frequency_utils.h"

#include "base/strings/stringprintf.h"
#include "base/system/sys_info.h"
#include "base/time/time.h"
#include "base/timer/elapsed_timer.h"
#include "base/trace_event/base_tracing.h"
#include "build/build_config.h"

#if BUILDFLAG(IS_WIN)
#include <windows.h>

#include <powerbase.h>
#include <processthreadsapi.h>
#include <winternl.h>
#endif

namespace base {
namespace {

#if BUILDFLAG(IS_WIN)
// From
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa373184(v=vs.85).aspx.
// Note that this structure definition was accidentally omitted from WinNT.h.
typedef struct _PROCESSOR_POWER_INFORMATION {
  ULONG Number;
  ULONG MaxMhz;
  ULONG CurrentMhz;
  ULONG MhzLimit;
  ULONG MaxIdleState;
  ULONG CurrentIdleState;
} PROCESSOR_POWER_INFORMATION, *PPROCESSOR_POWER_INFORMATION;
#endif

}  // namespace

double EstimateCpuFrequency() {}

std::optional<CpuThroughputEstimationResult> EstimateCpuThroughput() {}

BASE_EXPORT CpuFrequencyInfo GetCpuFrequencyInfo() {}

#if BUILDFLAG(IS_WIN)
void GenerateCpuInfoForTracingMetadata(base::Value::Dict* metadata) {
  size_t num_cpu = static_cast<size_t>(base::SysInfo::NumberOfProcessors());
  std::vector<PROCESSOR_POWER_INFORMATION> info(num_cpu);
  if (!NT_SUCCESS(CallNtPowerInformation(
          ProcessorInformation, nullptr, 0, &info[0],
          static_cast<ULONG>(sizeof(PROCESSOR_POWER_INFORMATION) * num_cpu)))) {
    return;
  }

  // Output information for each cores. The cores frequencies may differ due to
  // little/big cores.
  for (const auto& i : info) {
    const ULONG cpu_number = i.Number;

    // The maximum CPU frequency for a given core.
    metadata->Set(base::StringPrintf("cpu-max-frequency-core%lu", cpu_number),
                  static_cast<int>(i.MaxMhz));

    // The maximum CPU frequency that the power settings will allow. This
    // setting can be changed by the users or by changing the power plan.
    if (i.MhzLimit != i.MaxMhz) {
      metadata->Set(
          base::StringPrintf("cpu-limit-frequency-core%lu", cpu_number),
          static_cast<int>(i.MhzLimit));
    }

    // The MaxIdleState field contains the maximum supported C-state. The value
    // is zero when the C-State is not supported.
    if (i.MaxIdleState != 0) {
      metadata->Set(
          base::StringPrintf("cpu-max-idle-state-core%lu", cpu_number),
          static_cast<int>(i.MaxIdleState));
    }
  }
}
#endif

}  // namespace base