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; } |