JNIEXPORT jlong SIGAR_JNI(win32_Pdh_pdhAddCounter) (JNIEnv *env, jclass cur, jlong query, jstring cp) { HCOUNTER h_counter; HQUERY h_query = (HQUERY)query; PDH_STATUS status; LPCTSTR counter_path = JENV->GetStringChars(env, cp, NULL); /* Add the counter that created the data in the log file. */ status = PdhAddCounter(h_query, counter_path, 0, &h_counter); if (status == PDH_CSTATUS_NO_COUNTER) { /* if given counter does not exist, * try the same name w/ "/sec" appended */ TCHAR counter_sec[MAX_PATH]; lstrcpy(counter_sec, counter_path); lstrcat(counter_sec, _T("/sec")); status = PdhAddCounter(h_query, counter_sec, 0, &h_counter); } JENV->ReleaseStringChars(env, cp, counter_path); if (status != ERROR_SUCCESS) { win32_throw_exception(env, get_error_message(status)); return 0; } return (jlong)h_counter; }
/****************************************************************************** * * * Comments: counter is NULL if it is not in the collector, * * do not call it for PERF_COUNTER_ACTIVE counters * * * ******************************************************************************/ PDH_STATUS zbx_PdhAddCounter(const char *function, PERF_COUNTER_DATA *counter, PDH_HQUERY query, const char *counterpath, PDH_HCOUNTER *handle) { PDH_STATUS pdh_status; LPTSTR wcounterPath; wcounterPath = zbx_utf8_to_unicode(counterpath); if (ERROR_SUCCESS == (pdh_status = PdhAddCounter(query, wcounterPath, 0, handle)) && ERROR_SUCCESS == (pdh_status = PdhValidatePath(wcounterPath))) { if (NULL != counter) counter->status = PERF_COUNTER_INITIALIZED; zabbix_log(LOG_LEVEL_DEBUG, "%s(): PerfCounter '%s' successfully added", function, counterpath); } else { if (NULL != counter) counter->status = PERF_COUNTER_NOTSUPPORTED; zabbix_log(LOG_LEVEL_DEBUG, "%s(): unable to add PerfCounter '%s': %s", function, counterpath, strerror_from_module(pdh_status, L"PDH.DLL")); } zbx_free(wcounterPath); return pdh_status; }
SCTReturn SCTStatistics::Initialize() { PDH_STATUS status; // Initialize the flag indicating whether this object can read the system cpu usage or not. mCanReadCpu = true; // Create a query object to poll cpu usage. status = PdhOpenQuery(NULL, 0, &mQueryHandle); if(status != ERROR_SUCCESS) { mCanReadCpu = false; } // Set query object to poll all cpus in the system. status = PdhAddCounter(mQueryHandle, TEXT("\\Processor(_Total)\\% processor time"), 0, &mCounterHandle); if(status != ERROR_SUCCESS) { mCanReadCpu = false; } mLastSampleTime = GetTickCount(); mCpuUsage = 0; return OK; }
/** * カウンタハンドル作成し、登録します。 * * @param pszInstanceName インスタンス名 * @param pszCounterName カウンタ名 * @param hCounter カウンタハンドル格納先 * @return カウンタハンドルの登録に成功した場合は true 、失敗した場合は false */ static bool AddCounter( LPTSTR pszInstanceName, LPTSTR pszCounterName, PDH_HCOUNTER &hCounter ) { // 入力チェック if( NULL == pszInstanceName || NULL == pszCounterName ) { assert( !"入力エラー" ); return false; } // カウンターパスの作成 TCHAR szCounterPath[COUNTER_PATH_SIZE]; if( !MakeCounterPath( pszInstanceName, pszCounterName, szCounterPath, COUNTER_PATH_SIZE ) ) { return false; } // 作成したカウンターパスを要求ハンドルに登録。カウンターハンドルを得ておく。 if( ERROR_SUCCESS != PdhAddCounter( hQuery, szCounterPath, 0, &hCounter ) ) { return false; } return true; }
PerformanceCounter::PerformanceCounter(const wchar_t* object_name, const wchar_t* counter_name, const wchar_t* instance_name) : valid_(false), query_(NULL), counter_(NULL) { PDH_COUNTER_PATH_ELEMENTS elements{}; elements.szObjectName = const_cast<LPWSTR>(object_name); elements.szCounterName = const_cast<LPWSTR>(counter_name); elements.szInstanceName = const_cast<LPWSTR>(instance_name); DWORD length = 0; auto status = PdhMakeCounterPath(&elements, nullptr, &length, 0); if (status != PDH_MORE_DATA) return; std::wstring counter_path; counter_path.resize(length - 1); status = PdhMakeCounterPath(&elements, &counter_path[0], &length, 0); if (status != ERROR_SUCCESS) return; status = PdhOpenQuery(nullptr, 0, &query_); if (status != ERROR_SUCCESS) return; status = PdhAddCounter(query_, counter_path.c_str(), 0, &counter_); if (status != ERROR_SUCCESS) return; valid_ = PdhCollectQueryData(query_) == ERROR_SUCCESS; }
unsigned int PerfCounter::AddCounterRaw(const std::wstring& counterPath) { PDH_HCOUNTER counter; PdhAddCounter(m_query, counterPath.c_str(), NULL, &counter); m_counters.push_back(counter); return static_cast<unsigned int>(m_counters.size()); }
JNIEXPORT jint JNICALL Java_org_krakenapps_winapi_PerformanceCounter_addCounter(JNIEnv *env, jobject obj, jint queryHandle, jstring category, jstring counter, jstring instance, jstring machine) { PDH_HCOUNTER phCounter = NULL; PDH_HQUERY phQuery = (PDH_HQUERY)queryHandle; LPTSTR counterPath = NULL; PDH_COUNTER_PATH_ELEMENTS pathElement; DWORD dwSize = 0; PDH_STATUS stat = 0; jboolean isCopy = JNI_FALSE; memset(&pathElement, 0, sizeof(pathElement)); pathElement.szObjectName = category ? (LPTSTR)(*env)->GetStringChars(env, category, &isCopy) : NULL; pathElement.szCounterName = counter ? (LPTSTR)(*env)->GetStringChars(env, counter, &isCopy) : NULL; pathElement.szInstanceName = instance ? (LPTSTR)(*env)->GetStringChars(env, instance, &isCopy) : NULL; pathElement.szMachineName = machine ? (LPTSTR)(*env)->GetStringChars(env, machine, &isCopy) : NULL; if(pathElement.szMachineName) { stat = PdhConnectMachine(pathElement.szMachineName); if(stat != ERROR_SUCCESS) { fprintf(stderr, "Error in PdhConnectMachine:, 0x%x\n", stat); if(pathElement.szMachineName) (*env)->ReleaseStringChars(env, category, pathElement.szObjectName); (*env)->ReleaseStringChars(env, counter, pathElement.szCounterName); (*env)->ReleaseStringChars(env, instance, pathElement.szInstanceName); (*env)->ReleaseStringChars(env, machine, pathElement.szMachineName); return 0; } } PdhMakeCounterPath(&pathElement, NULL, &dwSize, 0); if(dwSize == 0) { fprintf(stderr, "Error in PdhMakeCounterPath\n"); (*env)->ReleaseStringChars(env, category, pathElement.szObjectName); (*env)->ReleaseStringChars(env, counter, pathElement.szCounterName); (*env)->ReleaseStringChars(env, instance, pathElement.szInstanceName); (*env)->ReleaseStringChars(env, machine, pathElement.szMachineName); return 0; } counterPath = (LPTSTR)malloc(sizeof(TCHAR)*dwSize); stat = PdhMakeCounterPath(&pathElement, counterPath, &dwSize, 0); (*env)->ReleaseStringChars(env, category, pathElement.szObjectName); (*env)->ReleaseStringChars(env, counter, pathElement.szCounterName); (*env)->ReleaseStringChars(env, instance, pathElement.szInstanceName); (*env)->ReleaseStringChars(env, machine, pathElement.szMachineName); if(stat != ERROR_SUCCESS) { fprintf(stderr, "Error in PdhMakeCounterPath: 0x%x\n", stat); return 0; } stat = PdhAddCounter(phQuery, counterPath, 0, &phCounter); if(stat != ERROR_SUCCESS) { fprintf(stderr, "Error in PdhAddCounter: 0x%x\n", stat); return 0; } free(counterPath); PdhCollectQueryData(phQuery); return (jint)phCounter; }
BOOL init_profile(LPTSTR counter_name, PDH_profile *prof) { BOOL ret = TRUE; prof->hQuery = NULL; prof->hCounter = NULL; prof->value = -1; __try { if (open_profile(prof)) { if (PdhValidatePath(counter_name) == ERROR_SUCCESS) ret = (PdhAddCounter(prof->hQuery, counter_name, 0, &(prof->hCounter)) == ERROR_SUCCESS); else ret = FALSE; } else { ret = FALSE; } } __except(EXCEPTION_EXECUTE_HANDLER) { ret = FALSE; } return (ret); }
unsigned int PerfCounter::AddInstanceCounter(const std::wstring& objectName, const std::wstring& counterName) { PDH_HCOUNTER counter; std::wstring fullCounterName = (boost::wformat(L"\\%1%(%2%)\\%3%") % objectName % m_instName % counterName).str(); PdhAddCounter(m_query, fullCounterName.c_str(), NULL, &counter); m_counters.push_back(counter); return static_cast<unsigned int>(m_counters.size()); }
/** * クエリーを追加 * * @return 成功した場合は true 、失敗した場合は false */ JNIEXPORT jboolean JNICALL Java_jp_co_acroquest_endosnipe_javelin_resource_proc_PerfCounter_addCounter (JNIEnv *env, jobject obj, jstring counterPath){ // 3回試行する。 if( !GetCurrentInstanceName( szCurrentInstanceName, INSTANCE_NAME_SIZE ) ) { if( !GetCurrentInstanceName( szCurrentInstanceName, INSTANCE_NAME_SIZE ) ) { if( !GetCurrentInstanceName( szCurrentInstanceName, INSTANCE_NAME_SIZE ) ) { return false; } } } AddCounterForProcess(szCurrentInstanceName); PdhAddCounter( hQuery, "\\Processor(_Total)\\% Privileged Time", 0, &hCounterSysCPUSys ); PdhAddCounter( hQuery, "\\Processor(_Total)\\% User Time", 0, &hCounterSysCPUUser ); PdhAddCounter( hQuery, "\\Paging File(_Total)\\% Usage", 0, &hCounterSysPageUsage ); PdhAddCounter( hQuery, "\\Process(_Total)\\Page File Bytes", 0, &hCounterSysPageBytes ); PdhAddCounter( hQuery, "\\Memory\\Pages Input/sec", 0, &hCounterSysPageIn ); PdhAddCounter( hQuery, "\\Memory\\Pages Output/sec", 0, &hCounterSysPageOut ); PdhAddCounter( hQuery, "\\Process(_Total)\\Handle Count", 0, &hCounterSysNumFDs ); return true; }
void InitUptimePerfCounter() { char perfcntrname[64]; DWORD pcnlen = sizeof(perfcntrname) - 8; PdhOpenQuery(NULL, 0, &hQuery); strcpy(perfcntrname, "\\System\\"); PdhLookupPerfNameByIndex(NULL, 674, perfcntrname + 8, &pcnlen); PdhAddCounter(hQuery, perfcntrname, 0, &hCounter); }
void PioletPoisoner::InitPerformanceCounters() { UINT timer_ret=1; int i; char iai_buf[1024]; DWORD iai_buf_len=1024; IP_ADAPTER_INFO *iai=(IP_ADAPTER_INFO *)iai_buf; GetAdaptersInfo(iai,&iai_buf_len); // Remove (,) and / from the description of the interface while(strchr(iai->Description,'(')!=NULL) { *strchr(iai->Description,'(')='['; } while(strchr(iai->Description,')')!=NULL) { *strchr(iai->Description,')')=']'; } while(strchr(iai->Description,'/')!=NULL) { *strchr(iai->Description,'/')='_'; } m_keynames[0]="\\Processor(0)\\% Processor Time"; m_keynames[1]="\\Network Interface("; m_keynames[1]+=iai->Description; m_keynames[1]+=")\\Bytes Total/sec"; m_keynames[2]="\\Network Interface("; m_keynames[2]+=iai->Description; m_keynames[2]+=")\\Current Bandwidth"; m_pdh=0; // Create the pdh query if(PdhOpenQuery(NULL,0,&m_pdh)) { MessageBox(NULL,"Error opening pdh query","Error",MB_OK); return; } // ADD A COUNTER TO THE QUERY for(i=0; i<3; i++) { PDH_STATUS error=PdhAddCounter(m_pdh,m_keynames[i].c_str(),NULL,&m_pdh_counters[i]); if(error) { MessageBox(NULL,"Error adding counter to the pdh query","Error",MB_OK); return; } } // m_dlg.SetTimer(6,TIMER_LENGTH*1000,0); }
PerfCounter::PerfCounter() { PdhOpenQuery(NULL, NULL, &m_query); HMODULE hProcess = GetModuleHandle(NULL); wchar_t fileNameBuf[MAX_PATH]; GetModuleFileName((HMODULE) hProcess, fileNameBuf, MAX_PATH); wchar_t baseNameBuf[MAX_PATH]; _wsplitpath_s(fileNameBuf, NULL, 0, NULL, 0, baseNameBuf, MAX_PATH, NULL, 0); m_processName = baseNameBuf; DWORD processId = GetProcessId(GetCurrentProcess()); //we need to figure out the correct instance name //start by asking for all the counters which match the process name std::wstring wildcard = (boost::wformat(L"\\Process(%1%*)\\ID Process") % m_processName).str(); wchar_t paths[1024]; DWORD size = 1024; PdhExpandWildCardPath(NULL, wildcard.c_str(), paths, &size, 0); //create each ProcessID counter, check its value to see if it's the one we want size_t len = wcslen(paths); wchar_t* pathPtr = paths; bool found = false; while(len != 0) { PDH_HCOUNTER counter; PdhAddCounter(m_query, pathPtr, NULL, &counter); PdhCollectQueryData(m_query); PDH_RAW_COUNTER counterValue; PdhGetRawCounterValue(counter, 0, &counterValue); PdhRemoveCounter(counter); if(counterValue.FirstValue == processId) { found = true; break; } pathPtr += len + 1; len = wcslen(pathPtr); } if(found) { //we've got our desired instance name, which is ProcessName#N const wchar_t* instStart = wcschr(wildcard.c_str(), L'(') + 1; const wchar_t* instEnd = wcschr(wildcard.c_str(), L')') - 1; m_instName = std::wstring(instStart, instEnd - instStart); } else { //oh well, just roll with what we've got m_instName = m_processName; } }
void CCpu::Init(void) { m_CanReadCPU=true; if(PdhOpenQuery(NULL,0,&m_QueryHandle)!=ERROR_SUCCESS) { m_CanReadCPU=false; } if(PdhAddCounter(m_QueryHandle, TEXT("\\Processor(_Total)\\% processor time"), 0, &m_CounterHandle)!=ERROR_SUCCESS) m_CanReadCPU=false; m_LastSampleTime=GetTickCount(); m_CPUUsage=0; }
//------------------------------------------------------------------------------------------------------------------ // getcpuload() // directly prints the CPU usage on screen. This function need to be called twice with a minimum of 1 seconds // delay (msdn guideline) to display something usefull. // Also returns the usage in percent 0-100 where 100 means the system is working at maximum capacity. // Note for multiprocessor systems: // If one CPU is working at max capacity the result will (if using (_total) for PdhAddCounter() ) show a maximum // workload of 50% unless the other CPU(s) is also working at max load. //------------------------------------------------------------------------------------------------------------------ int getcpuload() { static PDH_STATUS status; static PDH_FMT_COUNTERVALUE value; static HQUERY query; static HCOUNTER counter; static DWORD ret; static char runonce=1; char cput=0; if(runonce) { status = PdhOpenQuery(NULL, 0, &query); if(status != ERROR_SUCCESS) { printf("PdhOpenQuery() ***Error: 0x%X\n",status); return 0; } PdhAddCounter(query, TEXT("\\Processor(_Total)\\% Processor Time"),0,&counter); // A total of ALL CPU's in the system //PdhAddCounter(query, TEXT("\\Processor(0)\\% Processor Time"),0,&counter); // For systems with more than one CPU (Cpu0) //PdhAddCounter(query, TEXT("\\Processor(1)\\% Processor Time"),0,&counter); // For systems with more than one CPU (Cpu1) runonce=0; PdhCollectQueryData(query); // No error checking here return 0; } status = PdhCollectQueryData(query); if(status != ERROR_SUCCESS) { printf("PhdCollectQueryData() ***Error: 0x%X\n",status); if(status==PDH_INVALID_HANDLE) printf("PDH_INVALID_HANDLE\n"); else if(status==PDH_NO_DATA) printf("PDH_NO_DATA\n"); else printf("Unknown error\n"); return 0; } status = PdhGetFormattedCounterValue(counter, PDH_FMT_DOUBLE | PDH_FMT_NOCAP100 ,&ret, &value); if(status != ERROR_SUCCESS) { printf("PdhGetFormattedCounterValue() ***Error: 0x%X\n",status); return 0; } cput = value.doubleValue; printf("\n\nCPU Total usage: %3d%%\n",cput); return cput; }
int add_counter(const char *fullCounterPath, HCOUNTER *phCounter) { PDH_STATUS pdh_status; pdh_status = PdhAddCounter(h_query, fullCounterPath, 0, phCounter); if(pdh_status != ERROR_SUCCESS) { //sg_set_error(SG_ERROR_PDHADD, fullCounterPath); phCounter = NULL; return -1; } return 0; }
bool TextClass::Initialize() { bool result; PDH_STATUS status; // TIMER // Check to see if this system supports high performance timers. QueryPerformanceFrequency((LARGE_INTEGER*)&m_frequency); if (m_frequency == 0) { return false; } // Find out how many times the frequency counter ticks every millisecond. m_ticksPerMs = (float)(m_frequency / 1000); QueryPerformanceCounter((LARGE_INTEGER*)&m_startTime); // FPS // Initialize the counters and the start time. m_fps = 0; m_count = 0; m_startTimeFps = timeGetTime(); // CPU // Initialize the flag indicating whether this object can read the system cpu usage or not. m_canReadCpu = true; // Create a query object to poll cpu usage. status = PdhOpenQuery(NULL, 0, &m_queryHandle); if (status != ERROR_SUCCESS) { m_canReadCpu = false; } // Set query object to poll all cpus in the system. status = PdhAddCounter(m_queryHandle, TEXT("\\Processor(_Total)\\% processor time"), 0, &m_counterHandle); if (status != ERROR_SUCCESS) { m_canReadCpu = false; } // Initialize the start time and cpu usage. m_lastSampleTime = GetTickCount(); m_cpuUsage = 0; return true; }
void PerformanceManager::initialise() { //===== // FPS //===== m_fps = 0; m_frameCount = 0; m_fpsStart = timeGetTime(); //====== // CPU //====== PDH_STATUS status; // initialise the flag indicating whether this object can read the system cpu usage or not. m_canAccessCPU = true; // create a query object to poll cpu usage. status = PdhOpenQuery(NULL, 0, &m_queryHandle); if (status != ERROR_SUCCESS) { m_canAccessCPU = false; } // set query object to poll all cpus in the system. status = PdhAddCounter(m_queryHandle, TEXT("\\Processor(_Total)\\% processor time"), 0, &m_counterHandle); if (status != ERROR_SUCCESS) { m_canAccessCPU = false; } // initialise the start time and cpu usage. m_lastSampleTime = GetTickCount(); m_usage = 0; //======= // Timer //======= // Check to see if this system supports high performance timers QueryPerformanceFrequency((LARGE_INTEGER*)&m_frequency); // Find out how many times the frequency counter ticks every millisecond m_ticksPerMs = (float)(m_frequency / 1000); // get the system time QueryPerformanceCounter((LARGE_INTEGER*)&m_timerStart); }
JNIEXPORT jlong JNICALL Java_org_hyperic_hq_plugin_mssql_PDH_pdhAddCounter(JNIEnv *env, jclass, jlong query, jstring path) { HCOUNTER h_counter; HQUERY h_query = (HQUERY)query; PDH_STATUS status; LPCTSTR counter_path = (LPCTSTR)env->GetStringChars(path, NULL); status = PdhAddCounter(h_query, counter_path, 0, &h_counter); env->ReleaseStringChars(path, (const jchar *)counter_path); if (status != ERROR_SUCCESS) { plugin_throw_exception(env, get_error_message(status)); return 0; } return (jlong)h_counter; }
void Initialize( void ) { // Create a PDH Query for reading real-time data, and add the counter to it. PDH_STATUS status = PdhOpenQuery( NULL, 0, &m_hQuery ); if( status != ERROR_SUCCESS ) { m_hQuery = NULL; } else { // If we can't add this counter to our query, it's not a very useful // query. Later uses of this query will always fail. There isn't much // else we can do here, so just ignore the return value. ( void )PdhAddCounter( m_hQuery, m_szCounterPath, 0, &m_hCounter ); } }
double getCpuLoad(){ PDH_HCOUNTER Counter; DWORD dwType; PDH_FMT_COUNTERVALUE Value; double ret = 0; PDH_HQUERY cpu_load_query = NULL; if(PdhOpenQuery(NULL, 0, &cpu_load_query) == ERROR_SUCCESS) { if(PdhAddCounter(cpu_load_query, "\\Processor(_Total)\\% Processor Time", 0, &Counter) == ERROR_SUCCESS && PdhCollectQueryData(cpu_load_query) == ERROR_SUCCESS && PdhGetFormattedCounterValue(Counter, PDH_FMT_DOUBLE, &dwType, &Value) == ERROR_SUCCESS) { ret = (Value.doubleValue * getCpuNum()) / 100.0; } if (cpu_load_query) PdhCloseQuery(cpu_load_query); } return ret; }
bool TSmartServer::GetSysItemInfo(HQUERY hQuery, char *pszPath, DWORD nType, PDH_FMT_COUNTERVALUE& fmtValue) { DWORD dwType; HCOUNTER hCounter ; if( PdhAddCounter(hQuery, pszPath, 0, &hCounter) != ERROR_SUCCESS ) return false; if( PdhCollectQueryData(hQuery) != ERROR_SUCCESS ) return false; if( PdhGetFormattedCounterValue(hCounter, nType, &dwType, &fmtValue) != ERROR_SUCCESS ) return false; return true; }
uint64_t readSingleCounter(char* path) { PDH_HQUERY Query = NULL; PDH_HCOUNTER Counter; DWORD dwType; PDH_RAW_COUNTER Value; LONGLONG ret = 0; if(PdhOpenQuery(NULL, 0, &Query) == ERROR_SUCCESS) { if(PdhAddCounter(Query, path, 0, &Counter) == ERROR_SUCCESS && PdhCollectQueryData(Query) == ERROR_SUCCESS && PdhGetRawCounterValue(Counter, &dwType, &Value) == ERROR_SUCCESS) { ret = Value.FirstValue; } if (Query) PdhCloseQuery(Query); } return (uint64_t)ret; }
uint64_t readFormattedCounter(char* path) { PDH_HQUERY Query = NULL; PDH_HCOUNTER Counter; DWORD dwType; PDH_FMT_COUNTERVALUE Value; LONGLONG ret = 0; if(PdhOpenQuery(NULL, 0, &Query) == ERROR_SUCCESS) { if(PdhAddCounter(Query, path, 0, &Counter) == ERROR_SUCCESS && PdhCollectQueryData(Query) == ERROR_SUCCESS && PdhGetFormattedCounterValue(Counter, PDH_FMT_LARGE, &dwType, &Value) == ERROR_SUCCESS) { ret = Value.largeValue; } if (Query) PdhCloseQuery(Query); } return (uint64_t)ret; }
bool DXFrame::CPUCounter::Init(Window* window, DXManager* manager, Font* font) { m_CPUText->Init(window, manager, font); m_CPUText->SetScale(manager, font, 0.5f); PDH_STATUS status; status = PdhOpenQuery(NULL, 0, &m_HandleQuery); if (status != ERROR_SUCCESS) return false; status = PdhAddCounter( m_HandleQuery, TEXT("\\Процессор(_Total)\\% загруженности процессора"), 0, &m_HandleCounter); //TEXT("\\Process(explorer)\\% Processor Time") if (status != ERROR_SUCCESS) return false; m_LastSampleTime = (unsigned long)GetTickCount64(); m_CPUUsage = 0; return true; }
nsresult WinProcMon::Init() { PDH_HQUERY query; PDH_HCOUNTER counter; // Get a query handle to the Performance Data Helper PDH_STATUS status = PdhOpenQuery( NULL, // No log file name: use real-time source 0, // zero out user data token: unsued &query); if (status != ERROR_SUCCESS) { LOG(("PdhOpenQuery error = %X", status)); return NS_ERROR_FAILURE; } // Add a pre-defined high performance counter to the query. // This one is for the total CPU usage. status = PdhAddCounter(query, TotalCounterPath, 0, &counter); if (status != ERROR_SUCCESS) { PdhCloseQuery(query); LOG(("PdhAddCounter (_Total) error = %X", status)); return NS_ERROR_FAILURE; } // Need to make an initial query call to set up data capture. status = PdhCollectQueryData(query); if (status != ERROR_SUCCESS) { PdhCloseQuery(query); LOG(("PdhCollectQueryData (init) error = %X", status)); return NS_ERROR_FAILURE; } mQuery = query; mCounter = counter; return NS_OK; }
HRESULT ZeroProcessMonitor::CreateCpuUsageCounter() { // PDH Query 생성 PDH_STATUS pdhStatus = PdhOpenQuery(NULL, 0, &cpuUsageQuery); if (ERROR_SUCCESS != pdhStatus) { // TODO: 에러 처리 // pdhStatus ==> ErrorCode return E_FAIL; } // CPU 사용량 Query 문자열 TCHAR szCounterPath[MAX_PATH]; _stprintf_s(szCounterPath, _T("\\Process(%s)\\%% Processor Time"), processName); // CPU 사용량 카운터 추가 //pdhStatus = PdhAddCounter( m_hCpuUsageQuery, szCounterPath, 0, &m_hCpuUsageCounter ); pdhStatus = PdhAddCounter(cpuUsageQuery, L"\\Processor(_TOTAL)\\% Processor Time", 0, &cpuUsageCounter); //wprintf(L"%s\n",szCounterPath); if (ERROR_SUCCESS != pdhStatus) { // TODO: 에러 처리 // pdhStatus ==> ErrorCode return E_FAIL; } pdhStatus = PdhCollectQueryData(cpuUsageQuery); if (ERROR_SUCCESS != pdhStatus) { // TODO: 에러 처리 // pdhStatus ==> ErrorCode return E_FAIL; } return S_OK; }
uint32_t readMultiCounter(char* path, PPDH_RAW_COUNTER_ITEM *ppBuffer) { PDH_HQUERY Query = NULL; PDH_HCOUNTER Counter; DWORD bufSize = 0, itemCount = 0; uint32_t ret = 0; if(PdhOpenQuery(NULL, 0, &Query) == ERROR_SUCCESS) { if(PdhAddCounter(Query, path, 0, &Counter) == ERROR_SUCCESS && PdhCollectQueryData(Query) == ERROR_SUCCESS && PdhGetRawCounterArray(Counter, &bufSize, &itemCount, NULL) == PDH_MORE_DATA) { *ppBuffer = (PPDH_RAW_COUNTER_ITEM)my_calloc(bufSize); if(PdhGetRawCounterArray(Counter, &bufSize, &itemCount, *ppBuffer) == ERROR_SUCCESS) { ret = itemCount; if(ret > 0 && strncmp("_Total",ppBuffer[0][itemCount-1].szName,6) == 0) { ret--; // use readSingleCounter if you need _Total; } } } if (Query) PdhCloseQuery(Query); } return (uint32_t)ret; }
// Function name : CPerfMon::AddCounter // Description : Adds a counter to the query. // Return type : int ; -1 on fail, index to counter on success. // Argument : const char *pszCounterName // // R E V I S I O N S: // DATE PROGRAMMER CHANGES // int CPerfMon::AddCounter(const char *pszCounterName) { PPDHCOUNTERSTRUCT pCounter; pCounter = new PDHCOUNTERSTRUCT; if (!pCounter) return -1; // add to current query if (PdhAddCounter(m_hQuery, pszCounterName, (DWORD)pCounter, &(pCounter->hCounter)) != ERROR_SUCCESS) { delete pCounter; // clean mem return -1; } // insert counter into array(s) pCounter->nIndex = m_nNextIndex++; pCounter->lValue = 0; pCounter->nNextIndex = 0; pCounter->nOldestIndex = 0; pCounter->nRawCount = 0; m_aCounters.Add(pCounter); return pCounter->nIndex; }
BOOL QueryPerfData(printInfoStruct& pI) { PDH_HQUERY hQuery = NULL; PDH_HCOUNTER hCounter = NULL; PDH_FMT_COUNTERVALUE_ITEM *pDisplayValues = NULL; DWORD dwBufferSize = 0, dwItemCount = 0; if (pI.wsFullPath.empty()) { std::wcout << "No performance counter path given!\n"; return FALSE; } PDH_STATUS status = PdhOpenQuery(NULL, NULL, &hQuery); if (FAILED(status)) goto die; status = PdhAddCounter(hQuery, pI.wsFullPath.c_str(), NULL, &hCounter); if (FAILED(status)) goto die; status = PdhCollectQueryData(hQuery); if (FAILED(status)) goto die; /* /* Most counters need two queries to provide a value. /* Those which need only one will return the second. */ Sleep(pI.dwPerformanceWait); status = PdhCollectQueryData(hQuery); if (FAILED(status)) goto die; status = PdhGetFormattedCounterArray(hCounter, pI.dwRequestedType, &dwBufferSize, &dwItemCount, pDisplayValues); if (status != PDH_MORE_DATA) goto die; pDisplayValues = reinterpret_cast<PDH_FMT_COUNTERVALUE_ITEM*>(new BYTE[dwBufferSize]); status = PdhGetFormattedCounterArray(hCounter, pI.dwRequestedType, &dwBufferSize, &dwItemCount, pDisplayValues); if (FAILED(status)) goto die; switch (pI.dwRequestedType) { case (PDH_FMT_LONG): pI.dValue = pDisplayValues[0].FmtValue.longValue; case (PDH_FMT_LARGE) : pI.dValue = pDisplayValues[0].FmtValue.largeValue; default: pI.dValue = pDisplayValues[0].FmtValue.doubleValue; } delete[]pDisplayValues; return TRUE; die: FormatPDHError(status); delete[]pDisplayValues; return FALSE; }