获取CPU占用 无奈啊~~

chmdcr chmdcr 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
获取CPU占用率代码如下

HQUERY hQuery;
HCOUNTER *pCounterHandle;
PDH_STATUS pdhStatus;
PDH_FMT_COUNTERVALUE fmtValue;
DWORD ctrType;
//CHAR szPathBuffer[MAXPATH] = {'\0'};
CString szPathBuffer="";
int nRetCode = 0;

// Open the query object.
pdhStatus = PdhOpenQuery (0, 0, &hQuery);

pCounterHandle = (HCOUNTER *)GlobalAlloc(GPTR, sizeof(HCOUNTER));

CHAR szCounterBuffer[MAX_PATH];
PDH_COUNTER_PATH_ELEMENTS pdh_Path;
pdh_Path.szMachineName =NULL;
pdh_Path.szObjectName = "Processor";
pdh_Path.szInstanceName = "0"; //看资料说这里传0表示获取机器当前的CPU占用率可我这返回的怎么是99.999?
//还有如果在这写个进程名如(explorer) 就会得到error -1这个结果 这是为什么呢??
pdh_Path.szParentInstance = NULL;
pdh_Path.dwInstanceIndex = 0;
pdh_Path.szCounterName = "% Processor Time";
DWORD length=MAX_PATH;
// 产生完整的路径
PdhMakeCounterPath ( &pdh_Path, szCounterBuffer, &length, 0);
szPathBuffer = szCounterBuffer;

pdhStatus = PdhAddCounter (hQuery,
szPathBuffer,
0,
pCounterHandle);
// "Prime" counters that need two values to display a
// formatted value.
pdhStatus = PdhCollectQueryData (hQuery);

// Get the current value of this counter.
pdhStatus = PdhGetFormattedCounterValue (*pCounterHandle,
PDH_FMT_DOUBLE,
&ctrType,
&fmtValue);

CString strRes;
//fmtValue.doubleValue为所要的结果
if (pdhStatus == ERROR_SUCCESS)
strRes.Format("%.20g",fmtValue.doubleValue);
else
// Print the error value.
strRes.Format("error -1");


// Close the query.
pdhStatus = PdhCloseQuery (hQuery);

//return nRetCode;
return strRes;
...全文

相关推荐

评论 10
收藏 已收藏
分享
返回顶部
chmdcr
VC/MFC 16,550 成员 421,606 内容