글
Technical Article/펌 2004. 4. 19. 03:54프로세스별 CPU사용율 알아내기
제 목 프로세스별 CPU사용율 아라내기
작 성 자 김한석(khs09188) 첨 부
파 일
작성시각 2002-02-05 오후 11:53:49
조 회 수 1933
쩝 이거 알아내는라고 좀 뭐좀 빠졌습니다.
소스는 기본적으로 두부분으로 나뉘어져 있습니다.
첫부분은 현메모리에 떠 있는 프로세스의 정보를 취득
해오는 부분인데, 타스크메니저의 프로세스가 사용하는
것과 동일한 프로세스만 취득해옵니다. 왜냐면 phd함수를
사용해서 Enumerate하기 때문이죠. 그래서 두가지 프로세스
는 제외시켰습니다.(Idle, _Total).클클
그 다음은 pdh함수를 사용하여 위에서 취득한 프로세스별로
카운터를 설정하고 측정한후 그 결과값을얻을 수 있습니다.
이 소스를 가지고 많은 활용 할수 있으리라 믿습니다.
이 프로그램은 지정된 퍼센트이상인 프로세스만 추려내는
함수입니다.
좀더 나은 방법을 알고 계시다면 저에게도 좀 알려주시고요.
그럼 즐프하세요.
/*< Usage >*********************************************************************
*
* int GetProcessCpuUsage (
* inLimitPercent : Percent of CPU Usage Alarm Level ( 0~100 )
* )
* return value : 0 : Normal Ended
* -1 : Abnormally Ended
*
* Result Value :
* int ginRetProcessCount : Count of Result Process
* char gchRetProcess[MAX_PROCESS_COUNT][MAX_PROCESSNAME_LENGTH]
* : String Array of Result Process
*
* ##Caution : It must be included "pdh.lib"
*
********************************************************************************
*/
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <pdh.h>
#include <malloc.h>
/*******************************************************************
* *
* PreDefine Value *
* *
*******************************************************************/
#define CPU_WARN_LIMIT 90 /* Percent of CPU alarm limit */
#define MAX_PROCESS_COUNT 128 /* Count of Max Process on Memory */
#define MAX_PROCESSNAME_LENGTH 64 /* Length of Process Name */
#define MAX_EXCEPT_COUNT 2 /* Count of Except Process Name */
/*******************************************************************
* *
* Global Area for the Result Value *
* *
*******************************************************************/
int ginRetProcessCount; /* Count of Result */
char gchRetProcess[MAX_PROCESS_COUNT][MAX_PROCESSNAME_LENGTH];
/* Result of Process Name */
/*******************************************************************
* *
* Subroutine Start *
* *
*******************************************************************/
int GetProcessCpuUsage(int inLimitPercent)
{
/***************************************************************
* *
* Define Variables and Initialize *
* *
***************************************************************/
HQUERY hQuery;
HCOUNTER hCounter[MAX_PROCESS_COUNT];
char chCounterName[256];
PDH_FMT_COUNTERVALUE FmtValue;
int inRet = 0, i = 0;
int inExceptFoundFlg; /* Flag of Except Process Name exist */
int inProcessCount; /* Count of Process Name after fetch */
/* Result of Enumerate Process Name */
char chProcess [MAX_PROCESS_COUNT][MAX_PROCESSNAME_LENGTH];
/* Except Process Define Array */
char chExcepName[MAX_EXCEPT_COUNT][MAX_PROCESSNAME_LENGTH]
= {"Idle","_Total",};
PDH_STATUS pdhStatus = ERROR_SUCCESS;
LPTSTR szCounterListBuffer = NULL;
DWORD dwCounterListSize = 0;
LPTSTR szInstanceListBuffer = NULL;
DWORD dwInstanceListSize = 0;
LPTSTR szThisInstance = NULL;
inProcessCount = 0;
ginRetProcessCount = 0;
memset(chProcess, (char)NULL, sizeof(chProcess) );
memset(gchRetProcess, (char)NULL, sizeof(gchRetProcess));
/***************************************************************
* *
* Get the list of working processes on memory *
* *
***************************************************************/
// Determine the required buffer size for the data.
pdhStatus = PdhEnumObjectItems (
NULL, // reserved
NULL, // local machine
TEXT("Process"), // object to enumerate
szCounterListBuffer, // pass in NULL buffers
&dwCounterListSize, // an 0 length to get
szInstanceListBuffer, // required size
&dwInstanceListSize, // of the buffers in chars
PERF_DETAIL_WIZARD, // counter detail level
0);
if (pdhStatus == ERROR_SUCCESS)
{
// Allocate the buffers and try the call again.
szCounterListBuffer = (LPTSTR)malloc ((dwCounterListSize * sizeof
(TCHAR)));
szInstanceListBuffer = (LPTSTR)malloc ((dwInstanceListSize * sizeof
(TCHAR)));
if ((szCounterListBuffer != NULL) && (szInstanceListBuffer != NULL))
{
pdhStatus = PdhEnumObjectItems (
NULL, // reserved
NULL, // local machine
TEXT("Process"), // object to enumerate
szCounterListBuffer, // pass in NULL buffers
&dwCounterListSize, // an 0 length to get
szInstanceListBuffer, // required size
&dwInstanceListSize, // of the buffers in chars
PERF_DETAIL_WIZARD, // counter detail level
0);
if (pdhStatus == ERROR_SUCCESS)
{
// Walk the return instance list.
for (szThisInstance = szInstanceListBuffer;
*szThisInstance != 0;
szThisInstance += lstrlen(szThisInstance) + 1)
{
/* Check Except Process Name */
inExceptFoundFlg = 0;
for ( i = 0 ; i < MAX_EXCEPT_COUNT ; i++ )
{
if ( memcmp(szThisInstance, chExcepName[i], strlen
(chExcepName[i])) != 0 )
continue;
else
{
inExceptFoundFlg = 1;
break;
}
}
if ( !inExceptFoundFlg )
/* Set the process */
sprintf(chProcess[inProcessCount++], "%s",
szThisInstance);
}
}
}
else inRet = -1;
if (szCounterListBuffer != NULL) free (szCounterListBuffer);
if (szInstanceListBuffer != NULL) free (szInstanceListBuffer);
}
else inRet = -1;
/***************************************************************
* *
* Find the process over the limit *
* *
***************************************************************/
/* Open a query */
PdhOpenQuery(NULL, 0, &hQuery);
/* Add counter name */
for( i = 0 ; i < inProcessCount ; i++ )
{
memset( chCounterName, (char)NULL, sizeof(chCounterName) );
sprintf(chCounterName, "\\Process(%s#0)\\%% Processor Time", &chProcess
[i]);
PdhAddCounter(hQuery, chCounterName, 0, &hCounter[i]);
}
/* Get the data */
PdhCollectQueryData(hQuery);
Sleep(100);
PdhCollectQueryData(hQuery);
/* Find a result */
for( i = 0 ; i < inProcessCount ; i++ )
{
PdhGetFormattedCounterValue(hCounter[i], PDH_FMT_DOUBLE, NULL, &FmtValue);
if( (int)FmtValue.doubleValue >= inLimitPercent )
{
/* Found the process over the limit */
sprintf(gchRetProcess[ginRetProcessCount++], "%s", &chProcess[i]);
}
}
/* Close a query */
PdhCloseQuery(hQuery);
/* Normally Ended */
return 0;
}
/*******************************************************************
* *
* Subroutine End *
* *
*******************************************************************/
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
int inRet = 0;
/* Get the process over the limit */
inRet = GetProcessCpuUsage( CPU_WARN_LIMIT );
if( inRet )
{
/* Error */
return -1;
}
/* Normally Ended */
return 0;
}
작 성 자 김한석(khs09188) 첨 부
파 일
작성시각 2002-02-05 오후 11:53:49
조 회 수 1933
쩝 이거 알아내는라고 좀 뭐좀 빠졌습니다.
소스는 기본적으로 두부분으로 나뉘어져 있습니다.
첫부분은 현메모리에 떠 있는 프로세스의 정보를 취득
해오는 부분인데, 타스크메니저의 프로세스가 사용하는
것과 동일한 프로세스만 취득해옵니다. 왜냐면 phd함수를
사용해서 Enumerate하기 때문이죠. 그래서 두가지 프로세스
는 제외시켰습니다.(Idle, _Total).클클
그 다음은 pdh함수를 사용하여 위에서 취득한 프로세스별로
카운터를 설정하고 측정한후 그 결과값을얻을 수 있습니다.
이 소스를 가지고 많은 활용 할수 있으리라 믿습니다.
이 프로그램은 지정된 퍼센트이상인 프로세스만 추려내는
함수입니다.
좀더 나은 방법을 알고 계시다면 저에게도 좀 알려주시고요.
그럼 즐프하세요.
/*< Usage >*********************************************************************
*
* int GetProcessCpuUsage (
* inLimitPercent : Percent of CPU Usage Alarm Level ( 0~100 )
* )
* return value : 0 : Normal Ended
* -1 : Abnormally Ended
*
* Result Value :
* int ginRetProcessCount : Count of Result Process
* char gchRetProcess[MAX_PROCESS_COUNT][MAX_PROCESSNAME_LENGTH]
* : String Array of Result Process
*
* ##Caution : It must be included "pdh.lib"
*
********************************************************************************
*/
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <pdh.h>
#include <malloc.h>
/*******************************************************************
* *
* PreDefine Value *
* *
*******************************************************************/
#define CPU_WARN_LIMIT 90 /* Percent of CPU alarm limit */
#define MAX_PROCESS_COUNT 128 /* Count of Max Process on Memory */
#define MAX_PROCESSNAME_LENGTH 64 /* Length of Process Name */
#define MAX_EXCEPT_COUNT 2 /* Count of Except Process Name */
/*******************************************************************
* *
* Global Area for the Result Value *
* *
*******************************************************************/
int ginRetProcessCount; /* Count of Result */
char gchRetProcess[MAX_PROCESS_COUNT][MAX_PROCESSNAME_LENGTH];
/* Result of Process Name */
/*******************************************************************
* *
* Subroutine Start *
* *
*******************************************************************/
int GetProcessCpuUsage(int inLimitPercent)
{
/***************************************************************
* *
* Define Variables and Initialize *
* *
***************************************************************/
HQUERY hQuery;
HCOUNTER hCounter[MAX_PROCESS_COUNT];
char chCounterName[256];
PDH_FMT_COUNTERVALUE FmtValue;
int inRet = 0, i = 0;
int inExceptFoundFlg; /* Flag of Except Process Name exist */
int inProcessCount; /* Count of Process Name after fetch */
/* Result of Enumerate Process Name */
char chProcess [MAX_PROCESS_COUNT][MAX_PROCESSNAME_LENGTH];
/* Except Process Define Array */
char chExcepName[MAX_EXCEPT_COUNT][MAX_PROCESSNAME_LENGTH]
= {"Idle","_Total",};
PDH_STATUS pdhStatus = ERROR_SUCCESS;
LPTSTR szCounterListBuffer = NULL;
DWORD dwCounterListSize = 0;
LPTSTR szInstanceListBuffer = NULL;
DWORD dwInstanceListSize = 0;
LPTSTR szThisInstance = NULL;
inProcessCount = 0;
ginRetProcessCount = 0;
memset(chProcess, (char)NULL, sizeof(chProcess) );
memset(gchRetProcess, (char)NULL, sizeof(gchRetProcess));
/***************************************************************
* *
* Get the list of working processes on memory *
* *
***************************************************************/
// Determine the required buffer size for the data.
pdhStatus = PdhEnumObjectItems (
NULL, // reserved
NULL, // local machine
TEXT("Process"), // object to enumerate
szCounterListBuffer, // pass in NULL buffers
&dwCounterListSize, // an 0 length to get
szInstanceListBuffer, // required size
&dwInstanceListSize, // of the buffers in chars
PERF_DETAIL_WIZARD, // counter detail level
0);
if (pdhStatus == ERROR_SUCCESS)
{
// Allocate the buffers and try the call again.
szCounterListBuffer = (LPTSTR)malloc ((dwCounterListSize * sizeof
(TCHAR)));
szInstanceListBuffer = (LPTSTR)malloc ((dwInstanceListSize * sizeof
(TCHAR)));
if ((szCounterListBuffer != NULL) && (szInstanceListBuffer != NULL))
{
pdhStatus = PdhEnumObjectItems (
NULL, // reserved
NULL, // local machine
TEXT("Process"), // object to enumerate
szCounterListBuffer, // pass in NULL buffers
&dwCounterListSize, // an 0 length to get
szInstanceListBuffer, // required size
&dwInstanceListSize, // of the buffers in chars
PERF_DETAIL_WIZARD, // counter detail level
0);
if (pdhStatus == ERROR_SUCCESS)
{
// Walk the return instance list.
for (szThisInstance = szInstanceListBuffer;
*szThisInstance != 0;
szThisInstance += lstrlen(szThisInstance) + 1)
{
/* Check Except Process Name */
inExceptFoundFlg = 0;
for ( i = 0 ; i < MAX_EXCEPT_COUNT ; i++ )
{
if ( memcmp(szThisInstance, chExcepName[i], strlen
(chExcepName[i])) != 0 )
continue;
else
{
inExceptFoundFlg = 1;
break;
}
}
if ( !inExceptFoundFlg )
/* Set the process */
sprintf(chProcess[inProcessCount++], "%s",
szThisInstance);
}
}
}
else inRet = -1;
if (szCounterListBuffer != NULL) free (szCounterListBuffer);
if (szInstanceListBuffer != NULL) free (szInstanceListBuffer);
}
else inRet = -1;
/***************************************************************
* *
* Find the process over the limit *
* *
***************************************************************/
/* Open a query */
PdhOpenQuery(NULL, 0, &hQuery);
/* Add counter name */
for( i = 0 ; i < inProcessCount ; i++ )
{
memset( chCounterName, (char)NULL, sizeof(chCounterName) );
sprintf(chCounterName, "\\Process(%s#0)\\%% Processor Time", &chProcess
[i]);
PdhAddCounter(hQuery, chCounterName, 0, &hCounter[i]);
}
/* Get the data */
PdhCollectQueryData(hQuery);
Sleep(100);
PdhCollectQueryData(hQuery);
/* Find a result */
for( i = 0 ; i < inProcessCount ; i++ )
{
PdhGetFormattedCounterValue(hCounter[i], PDH_FMT_DOUBLE, NULL, &FmtValue);
if( (int)FmtValue.doubleValue >= inLimitPercent )
{
/* Found the process over the limit */
sprintf(gchRetProcess[ginRetProcessCount++], "%s", &chProcess[i]);
}
}
/* Close a query */
PdhCloseQuery(hQuery);
/* Normally Ended */
return 0;
}
/*******************************************************************
* *
* Subroutine End *
* *
*******************************************************************/
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
int inRet = 0;
/* Get the process over the limit */
inRet = GetProcessCpuUsage( CPU_WARN_LIMIT );
if( inRet )
{
/* Error */
return -1;
}
/* Normally Ended */
return 0;
}
![](https://lh3.googleusercontent.com/-hYZb_novCPQ/V5HuGPkGFUI/AAAAAAAAANk/f8zcKkeTBbA1A-W6yuqfk12fs8bd8FeOQCL0B/banner_468_60.png)
RECENT COMMENT