以下是使用 C++ 编写的示例代码,使用 OpenHardwareMonitorLib 获取 CPU 功耗:

#include <iostream>
#include <Windows.h>
#include 'OpenHardwareMonitorLib.h'

int main()
{
    OHM::OpenHardwareMonitorLib ohm;

    // 初始化 OpenHardwareMonitor
    if (!ohm.init()) {
        std::cout << 'Failed to initialize OpenHardwareMonitor.' << std::endl;
        return 1;
    }

    // 获取所有的硬件信息
    OHM::HardwareInfoList hardwareList = ohm.getHardwareInfo();

    // 查找 CPU
    OHM::HardwareInfo cpuInfo;
    for (const auto& hardware : hardwareList) {
        if (hardware.hardwareType == OHM::HardwareType::CPU) {
            cpuInfo = hardware;
            break;
        }
    }

    if (cpuInfo.hardwareType == OHM::HardwareType::Unknown) {
        std::cout << 'CPU not found.' << std::endl;
        return 1;
    }

    // 获取 CPU 功耗
    OHM::SensorInfo powerSensor;
    for (const auto& sensor : cpuInfo.sensors) {
        if (sensor.sensorType == OHM::SensorType::Power) {
            powerSensor = sensor;
            break;
        }
    }

    if (powerSensor.sensorType == OHM::SensorType::Unknown) {
        std::cout << 'CPU power sensor not found.' << std::endl;
        return 1;
    }

    // 循环读取 CPU 功耗
    while (true) {
        // 更新硬件信息
        ohm.update();

        // 查找 CPU
        OHM::HardwareInfo updatedCpuInfo;
        for (const auto& hardware : ohm.getHardwareInfo()) {
            if (hardware.hardwareType == OHM::HardwareType::CPU) {
                updatedCpuInfo = hardware;
                break;
            }
        }

        // 查找 CPU 功耗传感器
        OHM::SensorInfo updatedPowerSensor;
        for (const auto& sensor : updatedCpuInfo.sensors) {
            if (sensor.sensorType == OHM::SensorType::Power) {
                updatedPowerSensor = sensor;
                break;
            }
        }

        // 获取 CPU 功耗值
        float powerValue = ohm.getSensorValue(updatedPowerSensor);

        std::cout << 'CPU Power: ' << powerValue << ' W' << std::endl;

        // 延迟一段时间
        Sleep(1000);
    }

    return 0;
}

请确保已经将 OpenHardwareMonitorLib 的头文件和库文件正确添加到项目中,并根据需要进行相应的配置和调整。

C++ 获取 CPU 功耗:使用 OpenHardwareMonitorLib 库

原文地址: https://www.cveoy.top/t/topic/fwde 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录