如何使用C ++打印出当前的CPU使用率?我尝试在C ++ Builder中编译以下代码:
static PDH_HQUERY cpuQuery;
static PDH_HCOUNTER cpuTotal;
void init(){
PdhOpenQuery(NULL, NULL, &cpuQuery);
PdhAddCounter(cpuQuery, TEXT("\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal);
PdhCollectQueryData(cpuQuery);
}
double getCurrentValue(){
PDH_FMT_COUNTERVALUE counterVal;
PdhCollectQueryData(cpuQuery);
PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal);
Form1->Memo1->Lines->Add(String(counterVal.doubleValue));
return counterVal.doubleValue;
}
但我得到了错误的答案(3.124564654E-304)。如果我将TEXT("\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal);
更改为("\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal);
,我会得到正确答案(0)。
答案 0 :(得分:1)
显而易见的问题是,在初始化查询和显示结果的时间之间保持CPU的繁忙程度。
做一个快速测试,我似乎得到了合理的结果。
#include <windows.h>
#include <string>
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <atomic>
#include "pdh.h"
#pragma comment(lib, "pdh.lib")
class Query {
PDH_HQUERY cpuQuery;
PDH_HCOUNTER cpuTotal;
public:
Query() {
PdhOpenQuery(NULL, NULL, &cpuQuery);
PdhAddCounter(cpuQuery, TEXT("\\Processor(_Total)\\% Processor Time"), NULL, &cpuTotal);
PdhCollectQueryData(cpuQuery);
}
operator double() {
PDH_FMT_COUNTERVALUE counterVal;
PdhCollectQueryData(cpuQuery);
PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal);
return counterVal.doubleValue;
}
};
int main() {
Query q;
// First try a couple of seconds of relative quiescent:
Sleep(2000);
std::cout << q << "\n";
// Then a little while keeping the CPU busy:
volatile unsigned long long k=0;
#pragma omp parallel for reduction(+:k)
for (int i = 0; i < 1000000; i++)
for (int j = 0; j < 10000; j++)
++k;
std::cout << q << "\n";
}
我使用OpenMP编译(使用VC ++),如下所示:
cl /O2b2 /GL /openmp test.cpp
...并得到以下结果:
3.28491
98.9863
因此,当我离开系统空闲时,大约3%的CPU使用率,而当我保持忙碌时,大约为99%。我想你可以说后者真的应该接近100%,但至少对我而言,结果似乎还算合理。