Cpu 사용율 알아내는 소스
share this post
Visual C++에서 작업 하였다.
출력
CPU Usage : 57.8125%
CPU Usage : 40.625%
CPU Usage : 28.125%
CPU Usage : 29.6875%
CPU Usage : 18.1818%
CPU Usage : 21.875%
CPU Usage : 4.6875%
CPU Usage : 1.5625%
|
소스
|
#pragma comment(lib, "pdh.lib")
#include <windows.h>
#include <pdh.h>
#include <pdhmsg.h>
#include <iostream>
using namespace std;
class CpuUsage
{
private:
PDH_HQUERY m_hQuery;
PDH_HCOUNTER m_hCounter;
public:
CpuUsage() : m_hQuery( 0 ), m_hCounter( 0 ) {}
~CpuUsage() { destroy(); }
bool init()
{
PDH_STATUS status = PdhOpenQuery (0, 0, &m_hQuery);
if( status != ERROR_SUCCESS )
return false;
status = PdhAddCounter( m_hQuery, "\Processor(_TOTAL)\% Processor Time", 0, &m_hCounter );
if( status != ERROR_SUCCESS )
return false;
status = PdhCollectQueryData( m_hQuery );
if( status != ERROR_SUCCESS )
{
return false;
}
return true;
}
void destroy()
{
if( m_hQuery )
PdhCloseQuery( m_hQuery );
m_hQuery = 0;
}
bool getCpuUsage( double * val )
{
PDH_STATUS status = PdhCollectQueryData( m_hQuery );
if( status != ERROR_SUCCESS )
return false;
PDH_FMT_COUNTERVALUE value;
status = PdhGetFormattedCounterValue( m_hCounter, PDH_FMT_DOUBLE, 0, &value);
if (status != ERROR_SUCCESS)
return false;
*val = value.doubleValue;
return true;
}
};
int main( int argc, char * argv[] )
{
CpuUsage cpuUsage;
if( cpuUsage.init() == false )
return 1;
while( true )
{
double val = 0.0;
if( cpuUsage.getCpuUsage( &val ) )
cout << "CPU Usage : " << val << "%\n";
Sleep( 500 );
}
cout << "\t\thttp://fehead.tistory.com\n";
return 0;
}
|
[출처] http://fehead.tistory.com/80
본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.