获取CPU占用 无奈啊~~

chmdcr 2009-07-23 01:41:53
获取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;
...全文
140 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
chmdcr 2009-07-24
  • 打赏
  • 举报
回复
呵呵 好再开一个帖子 还有些问题
rendao0563 2009-07-23
  • 打赏
  • 举报
回复
要是真的感谢就多加点分比较实在。 其他都是假的。
chmdcr 2009-07-23
  • 打赏
  • 举报
回复
十分感谢 LS
rendao0563 2009-07-23
  • 打赏
  • 举报
回复
因为原来这个是单件
所以
private:
CProcessInfo();
~CProcessInfo();
你把挪到public里面去就好了。
rendao0563 2009-07-23
  • 打赏
  • 举报
回复

sprintf(szCPUDesc, "\\Process(%s)\\%s Processor Time", pszProc, "%");

_GetCounterValue(szCPUDesc);
Sleep(500);

return _GetCounterValue(szCPUDesc);
}

bool CProcessInfo::AddElapsedTimeCounter(const char * pszProc)
{
char szElapsedTimeDesc[512];
szElapsedTimeDesc[0] = '\0';

sprintf(szElapsedTimeDesc, "\\Process(%s)\\Elapsed Time", pszProc);

return _AddCounter(szElapsedTimeDesc);
}

DWORD CProcessInfo::GetElapsedTimeValue(const char * pszProc)
{
char szElapsedTimeDesc[512];
szElapsedTimeDesc[0] = '\0';

sprintf(szElapsedTimeDesc, "\\Process(%s)\\Elapsed Time", pszProc);

return _GetCounterValue(szElapsedTimeDesc);
}

bool CProcessInfo::AddMemoryCounter(const char * pszProc)
{
char szMemoryDesc[512];
szMemoryDesc[0] = '\0';

sprintf(szMemoryDesc, "\\Process(%s)\\Working Set", pszProc);

return _AddCounter(szMemoryDesc);
}

DWORD CProcessInfo::GetMemoryValue(const char * pszProc)
{
char szMemoryDesc[512];
szMemoryDesc[0] = '\0';

sprintf(szMemoryDesc, "\\Process(%s)\\Working Set", pszProc);

return _GetCounterValue(szMemoryDesc);
}

bool CProcessInfo::AddNetCounter(const char * pszIP, const char *pszDesc)
{
char szNetDesc[1024];
szNetDesc[0] = '\0';

sprintf(szNetDesc, "\\NetWork Interface(%s)\\%s", _GetAdaptersInfoByIP(pszIP), pszDesc);

return _AddCounter(szNetDesc);
}

DWORD CProcessInfo::GetNetValue(const char * pszIP, const char *pszDesc)
{
char szNetDesc[1024];
szNetDesc[0] = '\0';

sprintf(szNetDesc, "\\NetWork Interface(%s)\\%s", _GetAdaptersInfoByIP(pszIP), pszDesc);

return _GetCounterValue(szNetDesc);
}

bool CProcessInfo::AddCounter(const char * pszDesc)
{
return _AddCounter(pszDesc);
}

DWORD CProcessInfo::GetCounterValue(const char * pszDesc)
{
return _GetCounterValue(pszDesc);
}

DWORD CProcessInfo::_GetCounterValue(const char * pszDesc)
{
if(ERROR_SUCCESS == PdhCollectQueryData(m_hQuery))
{
HCOUNTER *pCounter = _FindHCounter(pszDesc);
if (pCounter != NULL)
{
PDH_FMT_COUNTERVALUE szFmtValue={0};
DWORD dwCtrType;
if(ERROR_SUCCESS == PdhGetFormattedCounterValue(*pCounter,
PDH_FMT_LONG, // PDH_FMT_DOUBLE,
&dwCtrType,
&szFmtValue))
{
return szFmtValue.longValue;
}
}
}

return -1;
}

bool CProcessInfo::_AddCounter(const char * pszDesc)
{
HCOUNTER* pca = (HCOUNTER *)GlobalAlloc(GPTR, (sizeof(HCOUNTER)));
m_oHCountMap[pszDesc] = pca;
return (ERROR_SUCCESS == PdhAddCounter(m_hQuery, pszDesc, 0, pca));
}

HCOUNTER *CProcessInfo::_FindHCounter(const char * pszDesc)
{
CHCOUNTERMap::iterator it = m_oHCountMap.find(pszDesc);
if (it == m_oHCountMap.end())
{
return NULL;
}
return it->second;
}

const char* CProcessInfo::_GetAdaptersInfoByIP(const char* pszIP)
{
if (NULL != m_pAdInfo)
{
delete [] m_pAdInfo;
m_pAdInfo = NULL;
}

ULONG buflen;
PIP_ADAPTER_INFO pAdInfo_c = NULL;

buflen = 0;
GetAdaptersInfo(m_pAdInfo, &buflen);
m_pAdInfo = (struct _IP_ADAPTER_INFO *)new UCHAR[buflen+1];

if (GetAdaptersInfo(m_pAdInfo, &buflen) == ERROR_SUCCESS)
{
do
{
if (0 == strcmp(pszIP, m_pAdInfo->IpAddressList.IpAddress.String))
{
return m_pAdInfo->Description;
}

} while ((m_pAdInfo->Next != NULL) && (m_pAdInfo = m_pAdInfo->Next));
}

return NULL;
}
rendao0563 2009-07-23
  • 打赏
  • 举报
回复

processinfo.h


#ifndef __PROCESSINFO_H__
#define __PROCESSINFO_H__

#include <pdh.h>
#include <Iphlpapi.h>
#include <string>
#include <hash_map>

using namespace std;
using namespace stdext;

#pragma comment(lib, "pdh.lib")
#pragma comment(lib, "Iphlpapi.lib")

#define PROCESSOR "\\Processor(%s)\\%s"
#define PROCESS "\\Process(%s)\\%s"

#define BYTE_RECV_SEC "Bytes Received/sec"
#define BYTE_SENT_SEC "Bytes Sent/sec"
#define BYTE_TOTAL_SEC "Bytes Total/sec"

#define PACKET_RECV_SEC "Packets Received/sec"
#define PACKET_SENT_SEC "Packets Sent/sec"
#define PACKET_TOTAL_SEC "Packets/sec"

typedef hash_map<string, HCOUNTER*> CHCOUNTERMap;

class CProcessInfo
{
public:
///初始化
bool Init();
///清空所有计数器
bool ReSetCollectQueryData();

///系统CPU占用率计数器
bool AddTotalCPUCounter();
DWORD GetTotalCPUValue();

///进程CPU占用率计数器
bool AddProcCPUCounter(const char * pszProc);
DWORD GetProcCPUValue(const char * pszProc);

///程序运行时间计数器
bool AddElapsedTimeCounter(const char * pszProc);
DWORD GetElapsedTimeValue(const char * pszProc);

///程序占用内存计数器
bool AddMemoryCounter(const char * pszProc);
DWORD GetMemoryValue(const char * pszProc);

///网络相关计数器
bool AddNetCounter(const char * pszIP, const char *pszDesc);
DWORD GetNetValue(const char * pszIP, const char *pszDesc);

///用户自定义计数器
bool AddCounter(const char * pszDesc);
DWORD GetCounterValue(const char * pszDesc);

///获取系统处理器个数
int GetProcNumber() { return m_nProcNumber; }
///获取系统物理内存总数
long GetTotalPhysMemory() { return m_nMemory; }
///获取可用物理内存数
long GetAvailPhysMemory();

protected:
///根据IP地址取网卡信息,如输入IP地址所对应的网卡不存在,返回空
const char* _GetAdaptersInfoByIP(const char* pszIP);
HCOUNTER *_FindHCounter(const char * pszDesc);

bool _AddCounter(const char * pszDesc);
DWORD _GetCounterValue(const char * pszDesc);

private:
int m_nProcNumber; //系统处理器个数
long m_nMemory; //系统物理内存总数(Byte)
int m_nCntrs;
HQUERY m_hQuery;
HCOUNTER* m_pca;
PDH_STATUS m_pdhStatus;

PIP_ADAPTER_INFO m_pAdInfo;

CHCOUNTERMap m_oHCountMap;

CProcessInfo();
~CProcessInfo();
};

#endif


processinfo.cpp



#include "ProcessInfo.h"

CProcessInfo::CProcessInfo()
:m_nProcNumber(0),m_nMemory(0),m_pAdInfo(NULL)
{
m_oHCountMap.clear();
}

CProcessInfo::~CProcessInfo()
{
if (NULL != m_pAdInfo)
{
delete [] m_pAdInfo;
m_pAdInfo = NULL;
}

ReSetCollectQueryData();
PdhCloseQuery(m_hQuery);
}

bool CProcessInfo::Init()
{
SYSTEM_INFO sInfo;
GetSystemInfo(&sInfo);

MEMORYSTATUS memst;
GlobalMemoryStatus(&memst);

m_nProcNumber = sInfo.dwNumberOfProcessors;
m_nMemory = (long)memst.dwTotalPhys;

return (ERROR_SUCCESS == PdhOpenQuery(0, 0, &m_hQuery));
}

long CProcessInfo::GetAvailPhysMemory()
{
MEMORYSTATUS memst;
GlobalMemoryStatus(&memst);
return (long)memst.dwAvailPhys;
}

bool CProcessInfo::ReSetCollectQueryData()
{
CHCOUNTERMap::iterator it = m_oHCountMap.begin();
while (it != m_oHCountMap.end())
{
if (ERROR_SUCCESS != PdhRemoveCounter((HCOUNTER)(*(it->second))))
{
int nErr = GetLastError();
}
if (GlobalFree(it->second) != NULL)
{
int nErr = GetLastError();
}
it->second = NULL;
it = m_oHCountMap.erase(it);
}

return true;
}

bool CProcessInfo::AddTotalCPUCounter()
{
char szCPUDesc[512];
szCPUDesc[0] = '\0';

sprintf(szCPUDesc, "\\Processor(_Total)\\%s Processor Time", "%");

return _AddCounter(szCPUDesc);
}

DWORD CProcessInfo::GetTotalCPUValue()
{
char szCPUDesc[512];
szCPUDesc[0] = '\0';

sprintf(szCPUDesc, "\\Processor(_Total)\\%s Processor Time", "%");

_GetCounterValue(szCPUDesc);
Sleep(500);

return _GetCounterValue(szCPUDesc);
}

bool CProcessInfo::AddProcCPUCounter(const char * pszProc)
{
char szCPUDesc[512];
szCPUDesc[0] = '\0';

sprintf(szCPUDesc, "\\Process(%s)\\%s Processor Time", pszProc, "%");

return _AddCounter(szCPUDesc);
}

DWORD CProcessInfo::GetProcCPUValue(const char * pszProc)
{
char szCPUDesc[512];
szCPUDesc[0] = '\0';

sprintf(szCPUDesc, "\\Process(%s)\\%s Processor Time", pszProc, "%");

_GetCounterValue(szCPUDesc);
Sleep(500);

return _GetCounterValue(szCPUDesc);
}

bool CProcessInfo::AddElapsedTimeCounter(const char * pszProc)
{
char szElapsedTimeDesc[512];
szElapsedTimeDesc[0] = '\0';

sprintf(szElapsedTimeDesc, "\\Process(%s)\\Elapsed Time", pszProc);

return _AddCounter(szElapsedTimeDesc);
}

DWORD CProcessInfo::GetElapsedTimeValue(const char * pszProc)
{
char szElapsedTimeDesc[512];
szElapsedTimeDesc[0] = '\0';

sprintf(szElapsedTimeDesc, "\\Process(%s)\\Elapsed Time", pszProc);

return _GetCounterValue(szElapsedTimeDesc);
}

bool CProcessInfo::AddMemoryCounter(const char * pszProc)
{
char szMemoryDesc[512];
szMemoryDesc[0] = '\0';

sprintf(szMemoryDesc, "\\Process(%s)\\Working Set", pszProc);

return _AddCounter(szMemoryDesc);
}

DWORD CProcessInfo::GetMemoryValue(const char * pszProc)
{
char szMemoryDesc[512];
szMemoryDesc[0] = '\0';

sprintf(szMemoryDesc, "\\Process(%s)\\Working Set", pszProc);

return _GetCounterValue(szMemoryDesc);
}

bool CProcessInfo::AddNetCounter(const char * pszIP, const char *pszDesc)
{
char szNetDesc[1024];
szNetDesc[0] = '\0';

sprintf(szNetDesc, "\\NetWork Interface(%s)\\%s", _GetAdaptersInfoByIP(pszIP), pszDesc);

return _AddCounter(szNetDesc);
}

DWORD CProcessInfo::GetNetValue(const char * pszIP, const char *pszDesc)
{
char szNetDesc[1024];
szNetDesc[0] = '\0';

sprintf(szNetDesc, "\\NetWork Interface(%s)\\%s", _GetAdaptersInfoByIP(pszIP), pszDesc);

return _GetCounterValue(szNetDesc);
}

bool CProcessInfo::AddCounter(const char * pszDesc)
{
return _AddCounter(pszDesc);
}

DWORD CProcessInfo::GetCounterValue(const char * pszDesc)
{
return _GetCounterValue(pszDesc);
}

DWORD CProcessInfo::_GetCounterValue(const char * pszDesc)
{
if(ERROR_SUCCESS == PdhCollectQueryData(m_hQuery))
{
HCOUNTER *pCounter = _FindHCounter(pszDesc);
if (pCounter != NULL)
{
PDH_FMT_COUNTERVALUE szFmtValue={0};
DWORD dwCtrType;
if(ERROR_SUCCESS == PdhGetFormattedCounterValue(*pCounter,
PDH_FMT_LONG, // PDH_FMT_DOUBLE,
&dwCtrType,
&szFmtValue))
{
return szFmtValue.longValue;
}
}
}

return -1;
}

bool CProcessInfo::_AddCounter(const char * pszDesc)
{
HCOUNTER* pca = (HCOUNTER *)GlobalAlloc(GPTR, (sizeof(HCOUNTER)));
m_oHCountMap[pszDesc] = pca;
return (ERROR_SUCCESS == PdhAddCounter(m_hQuery, pszDesc, 0, pca));
}

HCOUNTER *CProcessInfo::_FindHCounter(const char * pszDesc)
{
CHCOUNTERMap::iterator it = m_oHCountMap.find(pszDesc);
if (it == m_oHCountMap.end())
{
return NULL;
}
return it->second;
}

const char* CProcessInfo::_GetAdaptersInfoByIP(const char* pszIP)
{
if (NULL != m_pAdInfo)
{
delete [] m_pAdInfo;
m_pAdInfo = NULL;
}

ULONG buflen;
PIP_ADAPTER_INFO pAdInfo_c = NULL;

buflen = 0;
GetAdaptersInfo(m_pAdInfo, &buflen);
m_pAdInfo = (struct _IP_ADAPTER_INFO *)new UCHAR[buflen+1];

if (GetAdaptersInfo(m_pAdInfo, &buflen) == ERROR_SUCCESS)
{
do
{
if (0 == strcmp(pszIP, m_pAdInfo->IpAddressList.IpAddress.String))
{
return m_pAdInfo->Description;
}

} while ((m_pAdInfo->Next != NULL) && (m_pAdInfo = m_pAdInfo->Next));
}

return NULL;
}
danxuezx 2009-07-23
  • 打赏
  • 举报
回复
//   cpusagent.cpp   (Windows   NT/2000)   
//
// Getting the CPU usage in percent on Windows NT/2000
//
// (c)2000 Ashot Oganesyan K, SmartLine, Inc
// mailto:ashot@aha.ru, http://www.protect-me.com, http://www.codepile.com

#include <windows.h>
#include <conio.h>
#include <stdio.h>

#define SystemBasicInformation 0
#define SystemPerformanceInformation 2
#define SystemTimeInformation 3

#define Li2Double(x) ((double)((x).HighPart) * 4.294967296E9 + (double)((x).LowPart))

typedef struct
{
DWORD dwUnknown1;
ULONG uKeMaximumIncrement;
ULONG uPageSize;
ULONG uMmNumberOfPhysicalPages;
ULONG uMmLowestPhysicalPage;
ULONG uMmHighestPhysicalPage;
ULONG uAllocationGranularity;
PVOID pLowestUserAddress;
PVOID pMmHighestUserAddress;
ULONG uKeActiveProcessors;
BYTE bKeNumberProcessors;
BYTE bUnknown2;
WORD wUnknown3;
} SYSTEM_BASIC_INFORMATION;

typedef struct
{
LARGE_INTEGER liIdleTime;
DWORD dwSpare[76];
} SYSTEM_PERFORMANCE_INFORMATION;

typedef struct
{
LARGE_INTEGER liKeBootTime;
LARGE_INTEGER liKeSystemTime;
LARGE_INTEGER liExpTimeZoneBias;
ULONG uCurrentTimeZoneId;
DWORD dwReserved;
} SYSTEM_TIME_INFORMATION;


// ntdll!NtQuerySystemInformation (NT specific!)
//
// The function copies the system information of the
// specified type into a buffer
//
// NTSYSAPI
// NTSTATUS
// NTAPI
// NtQuerySystemInformation(
// IN UINT SystemInformationClass, // information type
// OUT PVOID SystemInformation, // pointer to buffer
// IN ULONG SystemInformationLength, // buffer size in bytes
// OUT PULONG ReturnLength OPTIONAL // pointer to a 32-bit
// // variable that receives
// // the number of bytes
// // written to the buffer
// );
typedef LONG (WINAPI *PROCNTQSI)(UINT,PVOID,ULONG,PULONG);

PROCNTQSI NtQuerySystemInformation;


void main(void)
{
SYSTEM_PERFORMANCE_INFORMATION SysPerfInfo;
SYSTEM_TIME_INFORMATION SysTimeInfo;
SYSTEM_BASIC_INFORMATION SysBaseInfo;
double dbIdleTime;
double dbSystemTime;
LONG status;
LARGE_INTEGER liOldIdleTime = {0,0};
LARGE_INTEGER liOldSystemTime = {0,0};

NtQuerySystemInformation = (PROCNTQSI)GetProcAddress(GetModuleHandle("ntdll"),"NtQuerySystemInformation");

if (!NtQuerySystemInformation)
return;

// get number of processors in the system
status = NtQuerySystemInformation(SystemBasicInformation,&SysBaseInfo,sizeof(SysBaseInfo),NULL);
if (status != NO_ERROR)
return;

printf("\nCPU Usage (press any key to exit): ");
while(!_kbhit())
{
// get new system time
status = NtQuerySystemInformation(SystemTimeInformation,&SysTimeInfo,sizeof(SysTimeInfo),0);
if (status!=NO_ERROR)
return;

// get new CPU's idle time
status =NtQuerySystemInformation(SystemPerformanceInformation,&SysPerfInfo,sizeof(SysPerfInfo),NULL);
if (status != NO_ERROR)
return;

// if it's a first call - skip it
if (liOldIdleTime.QuadPart != 0)
{
// CurrentValue = NewValue - OldValue
dbIdleTime = Li2Double(SysPerfInfo.liIdleTime) - Li2Double(liOldIdleTime);
dbSystemTime = Li2Double(SysTimeInfo.liKeSystemTime) -

Li2Double(liOldSystemTime);

// CurrentCpuIdle = IdleTime / SystemTime
dbIdleTime = dbIdleTime / dbSystemTime;

// CurrentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors
dbIdleTime = 100.0 - dbIdleTime * 100.0 /

(double)SysBaseInfo.bKeNumberProcessors + 0.5;

printf("\b\b\b\b%3d%%",(UINT)dbIdleTime);
}

// store new CPU's idle and system time
liOldIdleTime = SysPerfInfo.liIdleTime;
liOldSystemTime = SysTimeInfo.liKeSystemTime;

// wait one second
Sleep(1000);
}
printf("\n");
}

上面代码直接可以编译运行。如果您建的工程有stdafx.h文件的话,请include一下就好了。
chenyu2202863 2009-07-23
  • 打赏
  • 举报
回复
http://download.csdn.net/source/1003887
里面有源码
rendao0563 2009-07-23
  • 打赏
  • 举报
回复
LZ老是这么寒酸。这么点分。看了都提不起来精神。
  • 打赏
  • 举报
回复

16,472

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • Web++
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

试试用AI创作助手写篇文章吧