linux

Linux CPUInfo怎样获取CPU功耗

小樊
53
2025-08-16 05:13:16
栏目: 智能运维

在Linux系统中,可以通过读取/sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freq文件来获取当前CPU的频率。这个文件包含了CPU当前的运行频率(单位:kHz)。要计算CPU的功耗,需要知道CPU的电压和频率。

以下是一个简单的Python脚本,用于获取CPU的当前功耗:

import os

def get_cpu_frequency(cpu_id):
    freq_file = f"/sys/devices/system/cpu/cpu{cpu_id}/cpufreq/scaling_cur_freq"
    if os.path.exists(freq_file):
        with open(freq_file, 'r') as f:
            freq = int(f.read().strip()) / 1000  # Convert to MHz
        return freq
    else:
        return None

def get_cpu_voltage(cpu_id):
    voltage_file = f"/sys/devices/system/cpu/cpu{cpu_id}/cpufreq/scaling_cur_volt"
    if os.path.exists(voltage_file):
        with open(voltage_file, 'r') as f:
            voltage = float(f.read().strip()) / 1000000  # Convert to V
        return voltage
    else:
        return None

def calculate_power(cpu_id):
    freq = get_cpu_frequency(cpu_id)
    voltage = get_cpu_voltage(cpu_id)

    if freq is not None and voltage is not None:
        power = freq * voltage  # Power = Voltage * Frequency
        return power
    else:
        return None

cpu_id = 0  # Change this to the desired CPU core ID
power = calculate_power(cpu_id)

if power is not None:
    print(f"CPU {cpu_id} Power: {power:.2f} W")
else:
    print(f"Failed to get CPU {cpu_id} power information.")

请注意,这个脚本可能不适用于所有系统,因为某些系统可能需要root权限才能访问这些文件。此外,不是所有的CPU都支持动态电压和频率调整(DVFS),因此这个脚本可能无法在所有CPU上运行。

如果你需要更详细的功耗信息,可以考虑使用powertoptlp等工具。这些工具可以提供更全面的硬件功耗信息。

0
看了该问题的人还看了