C++-以赫兹(Windows)为单位查找当前CPU使用情况

C++ - Find current CPU usage in Hertz (Windows)

本文关键字:CPU 情况 用情 查找 为单位 Windows C++-      更新时间:2023-10-16

现状:
我想试着用赫兹来衡量我的系统当前的CPU利用率。

我已经看过这个解决我问题的答案,但我似乎无法使代码正常工作。

这是我当前在main.cpp中的代码(根据答案(:

#include <Pdh.h>
#include <PdhMsg.h>
#include <Windows.h>
static PDH_HQUERY cpuQuery;
static PDH_HCOUNTER cpuTotal;
void init()
{
    PDH_STATUS a = PdhOpenQuery(NULL, NULL, &cpuQuery);
    PDH_STATUS i = PdhAddCounter(cpuQuery, L"\Processor(_Total)\% Processor Time", NULL, &cpuTotal);
    PdhCollectQueryData(cpuQuery);
}
double getCurrentValue()
{
    init();
    PDH_FMT_COUNTERVALUE counterVal;
    PdhCollectQueryData(cpuQuery);
    PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal);
    return counterVal.doubleValue;
}
int main()
{
    double CPUUsage = getCurrentValue();
}

问题:
getCurrectValue()返回的值为零。

相关观察:
我观察到,PDH_STATUS类型的ai中的值都为零?我推测这可能与CPUUsage中缺少值有关,尽管我不确定为什么函数不能正确返回这些值。

其他信息:
我以前没用过PDH。

它是一个依赖于语言的PdhAddCoutner()。您应该使用PdhAddEnglishCounter()

编辑: init()中运行的查询和在getvalue()中运行的询问之间应该有最小延迟(500ms(。

其他解释:

在我的windows 8.1系统上运行您的代码,结果发现在init()中,i返回的状态是PDH_CSTATUS_NO_OBJECT,这意味着它没有找到对象"Processor(_Total("。

我首先认为这是一个拼写错误,并在Technet上验证了对象的名称和计数器。

出于好奇,我运行了最初的windows命令perfmon.exe,注意到所有的对象和计数器都是用我的母语翻译的。使用计数器的母语名称运行代码得到了正确的结果。

关于定时约束

一旦语言问题得到解决,通过一步一步的调试,我得到了CPU使用率的有意义的值。但一旦我删除了断点,我就得到了0或100。

因此,我在这个问题上做了进一步的研究,以了解微软的支持情况,即%费率需要在两个连续查询之间有一些最小的延迟。一旦我在init的出口添加了一个Sleep(1000),我就再次获得了有意义的CPU使用值。

/* Needed windows definitions by following header */
#include <windef.h>
/* Windows performance data helper */
#include <Pdh.h>
/* Storage of PDH query and associated cpu counter */
struct cpu_counter{
    PDH_HQUERY query;
    PDH_HCOUNTER counter;
};
/* Initialize query & counter */
int cpu_counter_init(struct cpu_counter* pcc)
{
    if(PdhOpenQueryA(NULL, 0, &pcc->query) != ERROR_SUCCESS)
        return -1;
    if(PdhAddEnglishCounterA(pcc->query, "\Processor(_Total)\% Processor Time", 0, &pcc->counter) != ERROR_SUCCESS || PdhCollectQueryData(pcc->query) != ERROR_SUCCESS)
    {
        PdhCloseQuery(pcc->query);
        return -2;
    }
    return 0;
}
/* Fetch data from query and evaluate current counter value */
int cpu_counter_get(struct cpu_counter* pcc)
{
    PDH_FMT_COUNTERVALUE counter_val;
    if(PdhCollectQueryData(pcc->query) != ERROR_SUCCESS || PdhGetFormattedCounterValue(pcc->counter, PDH_FMT_LONG, NULL, &counter_val) != ERROR_SUCCESS)
        return -1;
    return counter_val.longValue;
}
/* Close all counters of query and query itself at the end */
void cpu_counter_close(struct cpu_counter* pcc)
{
    if(pcc->query != NULL)
    {
        PdhCloseQuery(pcc->query);
        pcc->query = NULL;
    }
}

没有丑陋的静态、状态检查、使用实例而不是全局、最小包含、即使没有unicode定义也可以保存、内置Christophe的解决方案(plz宁愿支持他而不是我(。