[code=C/C++]/**************************************************************************************
* Source: cpucpu.c/cpp
* Description:
* This program can used to get the percent of CPU used, number of processes or
* theads, memory used, number of TCP connections ....
* Usage:
* The functions described above all depends on the "szPathBuffer"
*
* strcat(szPathBuffer,"//Processor(_Total)//% Processor Time");
*
* (Funtion):(szPathBuffer)
* CPU used percent: //Processor(_Total)//% Processor Time
* Number of process: //System//Processes
* Number of threads: //System//Threads
* Total Memory (Contains virtual memory): //Memory//Commit Limit
* Memory used (Contains virtual memory): //Memory//Committed Bytes
* Number of TCP connections: //TCP//Connections Active
*
* Other Object Items can get by PdhEnumObjects() and PdhEnumObjectItems()
*
* History:
* Jiazhen<luojiazhen#gmail.com> 26/02/2008
**************************************************************************************/
#include <pdh.h>
#include <CONIO.H>
#pragma comment( lib, "pdh.lib")
int main(int argc, char* argv[])
{
while( !_kbhit() )
{
HQUERY hQuery;
HCOUNTER *pCounterHandle;
PDH_STATUS pdhStatus;
PDH_FMT_COUNTERVALUE fmtValue;
DWORD ctrType;
CHAR szPathBuffer[MAXPATH] = {'/0'};
int nCPUUsage;
// Open the query object.
pdhStatus = PdhOpenQuery (0, 0, &hQuery);
pCounterHandle = (HCOUNTER *)GlobalAlloc(GPTR, sizeof(HCOUNTER));
// Get the CPU used information
strcat(szPathBuffer,"//Processor(_Total)//% Processor Time");
pdhStatus = PdhAddCounter (hQuery,
szPathBuffer,
0,
pCounterHandle);
pdhStatus = PdhCollectQueryData (hQuery);
// Get the current value of this counter.
pdhStatus = PdhGetFormattedCounterValue (*pCounterHandle,
PDH_FMT_DOUBLE,
&ctrType,
&fmtValue);
nCPUUsage = (int)fmtValue.doubleValue;
//fmtValue.doubleValue
if (pdhStatus == ERROR_SUCCESS) {
printf (TEXT(",/"%.20g/"/n"), fmtValue.doubleValue);
}
else {
// Print the error value.
printf ( TEXT("error./"-1/"") );
}
// Close the query.
pdhStatus = PdhCloseQuery (hQuery);
// Output the informaion
// printf("CPU Usage is %d/n", 100-nCPUUsage );
Sleep( 500 );
}
return 0;
}
[/code]
PdhCollectQueryData和获取系统信息
最新推荐文章于 2022-05-26 02:00:00 发布