获取CPU占用 无奈啊~~
获取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;
...全文
相关推荐
c#获取系统和指定进程的CPU和内存占用率
c#控制台示例程序 封装两个类 一个获取系统的CPU和内存占用率 一个获取指定进程的CPU和内存占用率 支持获取多个所有同名进程的信息
C++ 获取进程CPU占用率
主要介绍了C++ 获取进程CPU占用率,需要的朋友可以参考下
用java获取CPU占用率
用java获取CPU占用率 java 获取 CPU 占用率
vc 获取指定进程的cpu占用率和内存使用量
vs2008环境,vc编写的一个小工具,获取指定进程名字的cpu占用率和内存占用量,并按日期记录到ini配置文件中,支持多核cpu,如果有类似需求的,就不用再写代码了,下载下去看看吧。
WPF获取Windows系统内存占用和CPU占用
用wpf+visifire实现获取Windows系统内存占用和CPU占用,界面用Visifire.Gauges展现。


