/* Call before trying to get search results back, otherwise it'll be dead data */ int sg_win32_snapshot() { #ifdef WIN32 PDH_STATUS pdh_status; if(!is_started) { return -1; } pdh_status = PdhCollectQueryData(h_query); if(pdh_status != ERROR_SUCCESS) { sg_set_error(SG_ERROR_PDHCOLLECT, NULL); return -1; } #endif return 0; }
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; }
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; }
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; }
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; }
void SCTStatistics::CalculateCpuStats() { PDH_FMT_COUNTERVALUE value; if(mCanReadCpu) { if((mLastSampleTime + 1000) < GetTickCount()) { mLastSampleTime = GetTickCount(); PdhCollectQueryData(mQueryHandle); PdhGetFormattedCounterValue(mCounterHandle, PDH_FMT_LONG, NULL, &value); mCpuUsage = value.longValue; } } }
void DXFrame::CPUCounter::Update(DXManager* manager, Font* font) { PDH_FMT_COUNTERVALUE value; if ((m_LastSampleTime + 1000) < GetTickCount64()) { m_LastSampleTime = (unsigned long)GetTickCount64(); PdhCollectQueryData(m_HandleQuery); PdhGetFormattedCounterValue(m_HandleCounter, PDH_FMT_LONG, NULL, &value); m_CPUUsage = (int)value.longValue; m_CPUText->SetText(manager, font, "CPU:" + std::to_string(m_CPUUsage) + "%"); if (m_CPUUsage <= 30) m_CPUText->SetColor(D3DXVECTOR4(0.0f, 1.0f, 0.0f, 1.0f)); else if (m_CPUUsage >= 30 && m_CPUUsage < 60) m_CPUText->SetColor(D3DXVECTOR4(1.0f, 1.0f, 0.0f, 0.9f)); else if (m_CPUUsage >= 60) m_CPUText->SetColor(D3DXVECTOR4(1.0f, 0.0f, 0.0f, 0.9f)); } }
/** * Populates the host_memory structure using data retrieved using * GlobalMemoryStatusEx function and the Memory performance counter * object. * Returns FALSE if call to GlobalMemoryStatusEx produces an error, TRUE otherwise. * Note that the Windows use of memory and classification of use does * not map cleanly to Linux terms. * We are using Windows available memory for mem_free. Available memory * includes standby memory (memory removed from a process's working set * - its physical memory - on route to disk, but is still available to be recalled) * and free and zero page list bytes. Windows Resource Monitor reports free memory * as free page list bytes. * Memory\\Cache Bytes is used for mem_cached since this really does appear to be * the Linux equivalent of cache (file system cache). * Windows Resource Monitor reports cached as Standby+Modified this is not the * equivalent of Linux file system cache. * Windows also does not seem to report swapping (all memory associated with a process * swapped in/out of memory). Memory\\Pages Input/sec and Memory\\Pages Output/sec * are used for page_in and page_out. */ BOOL readMemoryCounters(SFLHost_mem_counters *mem) { MEMORYSTATUSEX memStat; memStat.dwLength = sizeof(memStat); if (GlobalMemoryStatusEx(&memStat) == 0){ myLog(LOG_ERR,"GlobalMemoryStatusEx failed: %d\n",GetLastError()); return FALSE; } mem->mem_total = memStat.ullTotalPhys; mem->mem_free = memStat.ullAvailPhys; mem->swap_total = memStat.ullTotalPageFile; mem->swap_free = memStat.ullAvailPageFile; PDH_HQUERY query; if (PdhOpenQuery(NULL, 0, &query) == ERROR_SUCCESS) { PDH_HCOUNTER cache, pageIn, pageOut; if (addCounterToQuery(MEM_COUNTER_OBJECT, NULL, MEM_COUNTER_CACHE, &query, &cache) == ERROR_SUCCESS && addCounterToQuery(MEM_COUNTER_OBJECT, NULL, MEM_COUNTER_PAGE_IN, &query, &pageIn) == ERROR_SUCCESS && addCounterToQuery(MEM_COUNTER_OBJECT, NULL, MEM_COUNTER_PAGE_OUT, &query, &pageOut) == ERROR_SUCCESS && PdhCollectQueryData(query) == ERROR_SUCCESS) { mem->mem_cached= getRawCounterValue(&cache); mem->page_in = (uint32_t)getRawCounterValue(&pageIn); mem->page_out = (uint32_t)getRawCounterValue(&pageOut); } PdhCloseQuery(query); } //There are no obvious Windows equivalents mem->mem_shared = UNKNOWN_COUNTER_64; mem->mem_buffers = UNKNOWN_COUNTER_64; //using the definition that swapping is when all the memory associated with a //process is moved in/out of RAM mem->swap_in = UNKNOWN_COUNTER; mem->swap_out = UNKNOWN_COUNTER; myLog(LOG_INFO, "readMemoryCounters:\n\ttotal: \t\t%I64d\n\tfree: \t\t%I64d\n" "\tcached: \t%I64d\n\tpage_in: \t%d\n\tpage_out: \t%d\n" "\tswap_total: \t%I64d\n\tswap_free: \t%I64d\n", mem->mem_total,mem->mem_free, mem->mem_cached,mem->page_in,mem->page_out, mem->swap_total, mem->swap_free); return TRUE; }
void InfoCPU::Update() { PDH_FMT_COUNTERVALUE value; if (mcanReadCpu) { if ((mlastSampleTime + 1000) < GetTickCount()) { mlastSampleTime = GetTickCount(); PdhCollectQueryData(mqueryHandle); PdhGetFormattedCounterValue(mcounterHandle, PDH_FMT_LONG, NULL, &value); mcpuUsage = value.longValue; } } return; }
// |----------------------------------------------------------------------------| // | Frame | // |----------------------------------------------------------------------------| void CpuClass::Frame() { PDH_FMT_COUNTERVALUE value; if(m_canReadCpu) { if((m_lastSampleTime + 1000) < GetTickCount()) { m_lastSampleTime = GetTickCount(); PdhCollectQueryData(m_queryHandle); PdhGetFormattedCounterValue(m_counterHandle, PDH_FMT_LONG, NULL, &value); m_cpuUsage = value.longValue; } } return; }
JNIEXPORT jdouble JNICALL Java_org_krakenapps_winapi_PerformanceCounter_nextValue(JNIEnv *env, jobject obj, jint queryHandle, jint counterHandle) { PDH_HQUERY phQuery = (PDH_HQUERY)queryHandle; PDH_HCOUNTER phCounter = (PDH_HCOUNTER)counterHandle; PDH_FMT_COUNTERVALUE pValue; PDH_STATUS stat = 0; stat = PdhCollectQueryData(phQuery); if(stat != ERROR_SUCCESS) { fprintf(stderr, "PdhCollectQueryData: 0x%x\n", stat); return 0; } stat = PdhGetFormattedCounterValue(phCounter, PDH_FMT_DOUBLE, NULL, &pValue); if(stat != ERROR_SUCCESS) { fprintf(stderr, "PdhGetFormattedCounterValue: 0x%x\n", stat); return 0; } return pValue.doubleValue; }
StatsRenderer::StatsRenderer(MPEVRCustomPresenter* presenter, IDirect3DDevice9* device): m_pPresenter(presenter), m_pD3DDev(device), m_pD3DXCreateLine(NULL), m_pD3DXCreateFont(NULL), m_pD3DXCreateSprite(NULL), m_hD3DX9Dll(NULL), m_pFont(NULL), m_pSprite(NULL), m_pLine(NULL) { HINSTANCE hDll; hDll = GetD3X9Dll(); if(hDll) { (FARPROC&)m_pD3DXCreateLine = GetProcAddress(hDll, "D3DXCreateLine"); (FARPROC&)m_pD3DXCreateFont = GetProcAddress(hDll, "D3DXCreateFontW"); (FARPROC&)m_pD3DXCreateSprite = GetProcAddress(hDll, "D3DXCreateSprite"); } if (m_pD3DXCreateSprite) { m_pD3DXCreateSprite( m_pD3DDev, &m_pSprite); } if (m_pD3DXCreateLine) { m_pD3DXCreateLine(m_pD3DDev, &m_pLine); } PDH_STATUS pdhStatus; PdhOpenQuery(NULL, NULL, &m_cpuQuery); pdhStatus = PdhAddEnglishCounter(m_cpuQuery, L"\\Processor(_Total)\\% Processor Time", NULL, &m_cpuTotal); if (pdhStatus == ERROR_SUCCESS) { PdhCollectQueryData(m_cpuQuery); } m_counter = 20; }
void CpuClass::Frame() { PDH_FMT_COUNTERVALUE value; if(m_canReadCpu) { // If it has been 1 second then update the current cpu usage and reset the 1 second timer again. if((m_lastSampleTime + 1000) < GetTickCount()) { m_lastSampleTime = GetTickCount(); PdhCollectQueryData(m_queryHandle); PdhGetFormattedCounterValue(m_counterHandle, PDH_FMT_LONG, NULL, &value); m_cpuUsage = value.longValue; } } return; }
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; }
int DiskTimeMuninNodePlugin::GetValues(char *buffer, int len) { PDH_STATUS status; PDH_FMT_COUNTERVALUE diskTimeValue; int printCount; status = PdhCollectQueryData(m_PerfQuery); if (status != ERROR_SUCCESS) return -1; for (size_t i = 0; i < m_DiskTimeCounters.size(); i++) { // Get the formatted counter value status = PdhGetFormattedCounterValue(m_DiskTimeCounters[i], PDH_FMT_DOUBLE, NULL, &diskTimeValue); if (status != ERROR_SUCCESS) return -1; printCount = _snprintf(buffer, len, "disktime_%i_.value %.2f\n", i, diskTimeValue.doubleValue); len -= printCount; buffer += printCount; } strncat(buffer, ".\n", len); return 0; }
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; }
static BOOL collect_profile(PDH_profile *prof) { BOOL ret = FALSE; PDH_FMT_COUNTERVALUE counter_val; PDH_STATUS rval; __try { if ((rval=PdhCollectQueryData(prof->hQuery)) == ERROR_SUCCESS) { if (PdhGetFormattedCounterValue(prof->hCounter, PDH_FMT_LONG, NULL, &counter_val) == ERROR_SUCCESS) { if (counter_val.CStatus == ERROR_SUCCESS) { prof->value = counter_val.longValue; ret = TRUE; } } } } __except(EXCEPTION_EXECUTE_HANDLER) { ret = FALSE; } return (ret); }
std::unique_ptr<char[]> PerformanceCounter::NextArray(DWORD format, DWORD* count) { auto status = PdhCollectQueryData(query_); if (status != ERROR_SUCCESS) return nullptr; DWORD length = 0; status = PdhGetFormattedCounterArray(counter_, format | PDH_FMT_NOCAP100, &length, count, nullptr); if (status != PDH_MORE_DATA) return nullptr; auto buffer = std::make_unique<char[]>(length); if (buffer == nullptr) return nullptr; auto items = reinterpret_cast<PDH_FMT_COUNTERVALUE_ITEM*>(buffer.get()); status = PdhGetFormattedCounterArray(counter_, format | PDH_FMT_NOCAP100, &length, count, items); if (status != ERROR_SUCCESS) return nullptr; return std::move(buffer); }
int main(int argc, char *argv[]) { struct sockaddr_in dest; int s; int slen = sizeof(dest); char message[BUFLEN]; WSADATA wsa; PDH_HQUERY hquery; PDH_HCOUNTER hcountercpu; PDH_STATUS status; PDH_FMT_COUNTERVALUE counterval; if (WSAStartup(MAKEWORD(2,2), &wsa) != 0) { fprintf(stderr, "WSAStartup %d\n", WSAGetLastError()); return 1; } dest.sin_family = AF_INET; dest.sin_port = htons(PORT); dest.sin_addr.s_addr = inet_addr(SERVER); if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) { fprintf(stderr, "socket %d\n", WSAGetLastError()); WSACleanup(); return 1; } if ((status = PdhOpenQuery(NULL, 0, &hquery)) != ERROR_SUCCESS) { fprintf(stderr, "PdhOpenQuery %lx\n", status); return 1; } if ((status = PdhAddCounter(hquery, COUNTER_PATH, 0, &hcountercpu)) != ERROR_SUCCESS) { fprintf(stderr, "PdhAddCounter (mem) %lx\n", status); return 1; } /* According to MSDN: Many counters, such as rate counters, require two data samples to calculate a formatted data value. http://msdn.microsoft.com/en-us/library/windows/desktop/aa371897(v=vs.85).aspx But it's not clear which counters might only require one. */ if ((status = PdhCollectQueryData(hquery)) != ERROR_SUCCESS) { fprintf(stderr, "PdhCollectQueryData %lx\n", status); return 1; } Sleep(INTERVAL); while (1) { if ((status = PdhCollectQueryData(hquery)) != ERROR_SUCCESS) { fprintf(stderr, "PdhCollectQueryData %lx\n", status); return 1; } if ((status = PdhGetFormattedCounterValue(hcountercpu, PDH_FMT_LARGE, 0, &counterval)) != ERROR_SUCCESS) { fprintf(stderr, "PdhGetFormattedCounterValue(cpu) %lx\n", status); return 1; } // %I64d is a MSVC thing sprintf_s(message, BUFLEN, "machine.mojave.memAvailable %I64d %d", counterval.largeValue, (unsigned)time(NULL)); printf("Sending %s\n", message); // Send plaintext to carbon server if (sendto(s, message, strlen(message), 0, (SOCKADDR*)&dest, slen) == SOCKET_ERROR) { fprintf(stderr, "sendto %d\n", WSAGetLastError()); if (closesocket(s) == SOCKET_ERROR) { fprintf(stderr, "closesocket %d\n", WSAGetLastError()); } WSACleanup(); return 1; } Sleep(INTERVAL); } if (closesocket(s) == SOCKET_ERROR) { fprintf(stderr, "closesocket %d\n", WSAGetLastError()); WSACleanup(); return 1; } WSACleanup(); return 0; }
bool GetPdhCounterValue(LPTSTR pszInstanceName, // インスタンス名 LPTSTR pszCounterName, // カウンター名 DWORD dwFormat, // 受け取る値の型の種類 void* pValue, // 値受け取りバッファー DWORD dwValueSize, // 値受け取りバッファーのサイズ(byte) DWORD dwSleepMilliSecond = 0) // [in]値受け取り時にスリープをするか { // 入力チェック if (NULL == pszInstanceName || NULL == pszCounterName || NULL == pValue || 0 == dwValueSize) { //assert( !"入力エラー" ); return false; } bool bResult = false; // 結果 HQUERY hQuery = NULL; // 要求ハンドル HCOUNTER hCounter = NULL; // カウンターハンドル // カウンターパスの作成 TCHAR szCounterPath[1024]; if (1 != MakeCounterPath(pszInstanceName, pszCounterName, szCounterPath, 1024)) { goto LABEL_END; } // 要求ハンドルの作成 if (ERROR_SUCCESS != PdhOpenQuery(NULL, 0, &hQuery)) // 要求ハンドル { goto LABEL_END; } // 作成したカウンターパスを要求ハンドルに登録。カウンターハンドルを得ておく。 if (ERROR_SUCCESS != PdhAddCounter(hQuery, // 要求ハンドル szCounterPath, 0, &hCounter)) // カウンターハンドル { goto LABEL_END; } // 要求データの取得 if (ERROR_SUCCESS != PdhCollectQueryData(hQuery)) { goto LABEL_END; } if (0 < dwSleepMilliSecond) { Sleep(dwSleepMilliSecond); if (ERROR_SUCCESS != PdhCollectQueryData(hQuery)) { goto LABEL_END; } } LABEL_END: PDH_FMT_COUNTERVALUE fmtValue; PdhGetFormattedCounterValue(hCounter, dwFormat, NULL, &fmtValue); bResult = true; PdhRemoveCounter(hCounter); PdhCloseQuery(hQuery); if (false == bResult) { // 失敗 //assert( !"失敗" ); return false; } // 成功 switch (dwFormat) { case PDH_FMT_LONG: if (dwValueSize != sizeof(LONG)) { //assert( !"受け取る値の型の種類に対して値受け取りバッファーのサイズが不正" ); return false; } else { LONG* plValue = (LONG*)pValue; *plValue = fmtValue.longValue; } break; case PDH_FMT_DOUBLE: if (dwValueSize != sizeof(double)) { //assert( !"受け取る値の型の種類に対して値受け取りバッファーのサイズが不正" ); return false; } else { double* pdValue = (double*)pValue; *pdValue = fmtValue.doubleValue; } break; case PDH_FMT_ANSI: case PDH_FMT_UNICODE: case PDH_FMT_LARGE: default: //assert( !"未対応" ); return false; } return true; }
bool DiskTimeMuninNodePlugin::OpenCounter() { PDH_STATUS status; OSVERSIONINFO osvi; ZeroMemory(&osvi, sizeof(OSVERSIONINFO)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); if (!GetVersionEx(&osvi) || (osvi.dwPlatformId != VER_PLATFORM_WIN32_NT)) return false; //unknown OS or not NT based // Create a PDH query status = PdhOpenQuery(NULL, 0, &m_PerfQuery); if (status != ERROR_SUCCESS) return false; TString logicalDiskCounterName = A2TConvert(g_Config.GetValue("DiskTimePlugin", "CounterNameLogicalDisk", "LogicalDisk")); TString diskTimeCounterName = A2TConvert(g_Config.GetValue("DiskTimePlugin", "CounterNameDiskTime", "% Disk Time")); DWORD counterListLength = 0; DWORD instanceListLength = 0; status = PdhEnumObjectItems(NULL, NULL, logicalDiskCounterName.c_str(), NULL, &counterListLength, NULL, &instanceListLength, PERF_DETAIL_EXPERT, 0); if (status != PDH_MORE_DATA) return false; TCHAR *counterList = new TCHAR[counterListLength]; TCHAR *instanceList = new TCHAR[instanceListLength]; counterList[0] = NULL; instanceList[0] = NULL; status = PdhEnumObjectItems(NULL, NULL, logicalDiskCounterName.c_str(), counterList, &counterListLength, instanceList, &instanceListLength, PERF_DETAIL_EXPERT, 0); if (status != ERROR_SUCCESS) { delete [] counterList; delete [] instanceList; return false; } int pos = 0; TCHAR *instanceName = instanceList; while (instanceName[0] != NULL && instanceName[1] != NULL) { std::string diskName = T2AConvert(instanceName); m_DiskTimeNames.push_back(diskName); while (instanceName[0] != NULL) instanceName++; instanceName++; } delete [] counterList; delete [] instanceList; // We drop the last instance name as it is _Total m_DiskTimeNames.pop_back(); TCHAR diskTimeCounterPath[MAX_PATH] = {0}; HCOUNTER diskTimeCounter; for (size_t i = 0; i < m_DiskTimeNames.size(); i++) { _sntprintf(diskTimeCounterPath, MAX_PATH, _T("\\%s(%s)\\%s"), logicalDiskCounterName.c_str(), m_DiskTimeNames[i].c_str(), diskTimeCounterName.c_str()); // Associate the uptime counter with the query status = PdhAddCounter(m_PerfQuery, diskTimeCounterPath, 0, &diskTimeCounter); if (status != ERROR_SUCCESS) return false; m_DiskTimeCounters.push_back(diskTimeCounter); } // Collect init data status = PdhCollectQueryData(m_PerfQuery); if (status != ERROR_SUCCESS) return false; return true; }
int __cdecl _tmain (int argc, TCHAR **argv) { HQUERY hQuery; PDH_STATUS pdhStatus; DWORD dwFormat = PDH_FMT_DOUBLE; PDH_FMT_COUNTERVALUE ItemBuffer; HCOUNTER hCounter; TCHAR szCounterPath[45] = TEXT("\\Processor(0)\\% Processor Time"); if (argc != 2) { DisplayCommandLineHelp (); return -1; } // Open a query object. pdhStatus = PdhOpenQuery (argv[1], 0, &hQuery); if( pdhStatus != ERROR_SUCCESS ) { _tprintf(TEXT("PdhOpenQuery failed with %ld\n"), pdhStatus); goto cleanup; } // Add the counter that created the data in the log file. pdhStatus = PdhAddCounter (hQuery, szCounterPath, 0, &hCounter); if( pdhStatus != ERROR_SUCCESS ) { _tprintf(TEXT("PdhAddCounter failed with %ld\n"), pdhStatus); goto cleanup; } // Read a performance data record. pdhStatus = PdhCollectQueryData(hQuery); if( pdhStatus != ERROR_SUCCESS ) { if ( pdhStatus != PDH_NO_MORE_DATA ) { _tprintf(TEXT("PdhCollectQueryData failed with %ld\n"), pdhStatus); } } while (pdhStatus == ERROR_SUCCESS) { // Format the performance data record. pdhStatus = PdhGetFormattedCounterValue (hCounter, dwFormat, (LPDWORD)NULL, &ItemBuffer); if (pdhStatus == ERROR_SUCCESS) { // Print the performance data record. _tprintf(TEXT("\nLog Record Value = %4.8f\n"), ItemBuffer.doubleValue); } else { _tprintf(TEXT("\nPdhGetFormattedCounterValue failed with %ld.\n"), pdhStatus); goto cleanup; } // Read the next record pdhStatus = PdhCollectQueryData(hQuery); if( pdhStatus != ERROR_SUCCESS ) { if ( pdhStatus != PDH_NO_MORE_DATA ) { _tprintf(TEXT("PdhCollectQueryData failed with %ld\n"), pdhStatus); } } } cleanup: // Close the query. if (hQuery) PdhCloseQuery (hQuery); return pdhStatus; }
/* * Instantiate a value for a single metric-instance pair */ int windows_collect_metric(pdh_metric_t *mp, LPSTR pat, pdh_value_t *vp) { PDH_STATUS pdhsts; PDH_HQUERY queryhdl = NULL; PDH_HCOUNTER counthdl = NULL; int sts = -1; if (mp->flags & M_NOVALUES) return sts; pdhsts = PdhOpenQueryA(NULL, 0, &queryhdl); if (pdhsts != ERROR_SUCCESS) { __pmNotifyErr(LOG_ERR, "windows_open: PdhOpenQueryA failed: %s\n", pdherrstr(pdhsts)); return sts; } pdhsts = PdhAddCounterA(queryhdl, pat, vp->inst, &counthdl); if (pdhsts != ERROR_SUCCESS) { __pmNotifyErr(LOG_ERR, "windows_open: Warning: PdhAddCounterA " "@ pmid=%s pat=\"%s\": %s\n", pmIDStr(mp->desc.pmid), pat, pdherrstr(pdhsts)); PdhCloseQuery(queryhdl); return sts; } pdhsts = PdhCollectQueryData(queryhdl); if (pdhsts != ERROR_SUCCESS) { if ((vp->flags & V_ERROR_SEEN) == 0) { __pmNotifyErr(LOG_ERR, "pdh_fetch: Error: PdhCollectQueryData " "failed for metric %s pat %s: %s\n", pmIDStr(mp->desc.pmid), pat, pdherrstr(pdhsts)); vp->flags |= V_ERROR_SEEN; } } else if ((mp->ctype == PERF_ELAPSED_TIME) || mp->ctype == PERF_LARGE_RAW_FRACTION) { PDH_FMT_COUNTERVALUE fmt; DWORD type; if (mp->ctype == PERF_ELAPSED_TIME) type = PDH_FMT_LARGE; else /* PERF_LARGE_RAW_FRACTION */ type = PDH_FMT_DOUBLE; pdhsts = PdhGetFormattedCounterValue(counthdl, type, NULL, &fmt); if (pdhsts != ERROR_SUCCESS) { __pmNotifyErr(LOG_ERR, "Error: PdhGetFormattedCounterValue " "failed for metric %s inst %d: %s\n", pmIDStr(mp->desc.pmid), vp->inst, pdherrstr(pdhsts)); vp->flags = V_NONE; /* no values for you! */ } else if (mp->ctype == PERF_ELAPSED_TIME) { vp->atom.ull = fmt.largeValue; sts = 0; } else { /* PERF_LARGE_RAW_FRACTION */ vp->atom.d = fmt.doubleValue; sts = 0; } } else { PDH_RAW_COUNTER raw; pdhsts = PdhGetRawCounterValue(counthdl, NULL, &raw); if (pdhsts != ERROR_SUCCESS) { __pmNotifyErr(LOG_ERR, "pdh_fetch: Error: PdhGetRawCounterValue " "failed for metric %s inst %d: %s\n", pmIDStr(mp->desc.pmid), vp->inst, pdherrstr(pdhsts)); vp->flags = V_NONE; /* no values for you! */ } else { switch (mp->ctype) { case PERF_COUNTER_COUNTER: case PERF_COUNTER_RAWCOUNT: /* these counters are only 32-bit */ vp->atom.ul = (__uint32_t)raw.FirstValue; break; case PERF_100NSEC_TIMER: case PERF_PRECISION_100NS_TIMER: /* convert 100nsec units to usec */ vp->atom.ull = raw.FirstValue / 10; break; case PERF_RAW_FRACTION: /* v1 / v2 as percentage */ vp->atom.f = (float)raw.FirstValue / raw.SecondValue; break; case PERF_COUNTER_BULK_COUNT: case PERF_COUNTER_LARGE_RAWCOUNT: default: vp->atom.ull = raw.FirstValue; } sts = 0; } } PdhRemoveCounter(counthdl); PdhCloseQuery(queryhdl); return sts; }
void PerfCounter::Update() { PdhCollectQueryData(m_query); }
vm_status vm_sys_info_cpu_loading_avg(struct VM_SYSINFO_CPULOAD *dbuf, Ipp32u timeslice/* in msec */) { PDH_STATUS sts = ERROR_SUCCESS; HQUERY tmpq = 0; vm_status rtval = VM_NULL_PTR; vm_char scountername[MAX_COUNTER_NAME]; PDH_HCOUNTER cptr = NULL; BOOL isprepared = FALSE; DWORD t; PDH_FMT_COUNTERVALUE v; int i; /* we need 1 ms period to hold timeslice time correct */ timeBeginPeriod(ONEMILLISECOND); do { #ifdef VM_CHECK_CPU_CHECK_TIMESLICE if (timeslice < 10) { rtval = VM_NOT_ENOUGH_DATA; break; } #endif if (dbuf == NULL) { dbuf = (struct VM_SYSINFO_CPULOAD *)malloc(sizeof(struct VM_SYSINFO_CPULOAD)); if (dbuf != NULL) dbuf[0].cpudes = NULL; } if (dbuf == NULL) break; if (dbuf[0].ncpu == 0) break; if (dbuf[0].cpudes == NULL) { dbuf[0].ncpu = vm_sys_info_get_cpu_num(); dbuf[0].cpudes = (struct VM_SYSINFO_CPULOAD_ENTRY *)(malloc(sizeof(struct VM_SYSINFO_CPULOAD_ENTRY)*(dbuf[0].ncpu+1))); } if (dbuf[0].cpudes == NULL) break; /* if cpu description buffer was not NULL I hope it will be enough to hold all information about all the CPUs */ tmpq = dbuf[0].CpuLoadQuery; if ( tmpq == 0) {/* no more performance handle created yet */ PdhOpenQuery(NULL, 0, &tmpq); if (tmpq == 0) break; dbuf[0].CpuLoadQuery = tmpq; } if (dbuf[0].CpuPerfCounters[0] != 0) isprepared = TRUE; /* performance monitor already prepared */ if (dbuf[0].CpuLoadQuery == 0) break; if (!isprepared) { /* create buffers for counters */ rtval = VM_OK; for( i = 0; i < MAX_PERF_PARAMETERS; ++i ) { dbuf[0].CpuPerfCounters[i] = NULL; dbuf[0].CpuPerfCounters[i] = (PDH_HCOUNTER *)malloc((dbuf[0].ncpu+1/*for overall counter*/)*sizeof(PDH_HCOUNTER)); if (dbuf[0].CpuPerfCounters[i] == NULL) { rtval = VM_OPERATION_FAILED; break; } } if (rtval != VM_OK) { for( i = 0; i < MAX_PERF_PARAMETERS; ++i ) if (dbuf[0].CpuPerfCounters[i] != NULL) { free(dbuf[0].CpuPerfCounters[i]); dbuf[0].CpuPerfCounters[i] = NULL; } break; } /* add performance counters */ /* user time */ vm_string_strcpy(scountername, VM_STRING("\\Processor ")); for( i = 0; i < dbuf[0].ncpu; ++i ) { vm_string_sprintf(&scountername[10], VM_STRING("(%d)\\%% User Time"), i); cptr = dbuf[0].CpuPerfCounters[0] + i*sizeof(PDH_HCOUNTER); sts = PdhAddCounter(dbuf[0].CpuLoadQuery, scountername, 0, cptr); vm_string_sprintf(&scountername[10], VM_STRING("(%d)\\%% Privileged Time"), i); cptr = dbuf[0].CpuPerfCounters[1] + i*sizeof(PDH_HCOUNTER); sts = PdhAddCounter(dbuf[0].CpuLoadQuery, scountername, 0, cptr); vm_string_sprintf(&scountername[10], VM_STRING("(%d)\\%% Interrupt Time"), i); cptr = dbuf[0].CpuPerfCounters[2] + i*sizeof(PDH_HCOUNTER); sts = PdhAddCounter(dbuf[0].CpuLoadQuery, scountername, 0, cptr); } } vm_time_sleep(timeslice); if ((sts = PdhCollectQueryData(dbuf[0].CpuLoadQuery)) != ERROR_SUCCESS) break; /* fill in output data structure */ for(i = 0; i < dbuf[0].ncpu; ++i) { sts = PdhGetFormattedCounterValue(dbuf[0].CpuPerfCounters[0][i], PDH_FMT_LONG, &t, &v); dbuf[0].cpudes[i].usrload = AVGFLOAT(v.longValue); sts = PdhGetFormattedCounterValue(dbuf[0].CpuPerfCounters[1][i], PDH_FMT_LONG, &t, &v); dbuf[0].cpudes[i].sysload = AVGFLOAT(v.longValue); dbuf[0].cpudes[i].idleload = (float)1. - dbuf[0].cpudes[i].usrload - dbuf[0].cpudes[i].sysload; dbuf[0].cpudes[i].idleload = (dbuf[0].cpudes[i].idleload < 0) ? 0 : dbuf[0].cpudes[i].idleload; sts = PdhGetFormattedCounterValue(dbuf[0].CpuPerfCounters[2][i], PDH_FMT_LONG, &t, &v); dbuf[0].cpudes[i].irqsrvload = AVGFLOAT(v.longValue); /* clear other parameters for each processor */ dbuf[0].cpudes[i].iowaitsload = dbuf[0].cpudes[i].softirqsrvload = 0.; dbuf[0].cpudes[i].usrniceload = dbuf[0].cpudes[i].vmstalled = 0.; } rtval = VM_OK; } while (0); if ((NULL != dbuf) && (ticks_on_avg_call != 0)) dbuf[0].tickspassed = (vm_tick)((vm_time_get_tick() - ticks_on_avg_call)*1000/vm_time_get_frequency()); ticks_on_avg_call = vm_time_get_tick(); timeEndPeriod(ONEMILLISECOND); return rtval; }
static int WINAPI sample_load(void *thr_data) { HQUERY hQuery = NULL; HCOUNTER hCounterQueueLength, *hCounterCpuLoad; int nextsample = 0, i, exit_status = 0; PDH_STATUS pdhStatus; PDH_FMT_COUNTERVALUE counterval; long queuelen; double cpuload; char counterpath[35]; EnterCriticalSection(&cs); for (i=0; i < NUM_SAMPLES; i++) { samples[i].load = 0; samples[i].sampletime = (time_t)0; } LeaveCriticalSection(&cs); if(!pdhAddCounterPtr) { if(!pdhModule) { pdhModule = GetModuleHandle(TEXT("pdh")); } if(pdhModule) pdhAddCounterPtr = (PdhAddCounterPtr)GetProcAddress(pdhModule, "PdhAddEnglishCounterA"); if(!pdhAddCounterPtr) pdhAddCounterPtr = PdhAddCounter; } pdhStatus = PdhOpenQuery(NULL, 0, &hQuery); if (pdhStatus != ERROR_SUCCESS) { /* dprintf(D_ALWAYS, "PdhOpenQuery returns 0x%x\n", (int)pdhStatus); */ return pdhStatus; } pdhStatus = pdhAddCounterPtr(hQuery, "\\System\\Processor Queue Length", 0, &hCounterQueueLength); if (pdhStatus != ERROR_SUCCESS) { /* dprintf(D_ALWAYS, "PdhAddCounter returns 0x%x\n", (int)pdhStatus); */ PdhCloseQuery(hQuery); return pdhStatus; } hCounterCpuLoad = (HCOUNTER *) malloc(sizeof(HCOUNTER)*ncpus); ASSERT( hCounterCpuLoad ); for (i=0; i < ncpus; i++) { sprintf(counterpath, "\\Processor(%d)\\%% Processor Time", i); pdhStatus = pdhAddCounterPtr(hQuery, counterpath, 0, hCounterCpuLoad+i); if (pdhStatus != ERROR_SUCCESS) { /* dprintf(D_ALWAYS, "PdhAddCounter returns 0x%x\n", (int)pdhStatus); */ PdhCloseQuery(hQuery); return pdhStatus; } } while (1) { pdhStatus = PdhCollectQueryData(hQuery); if (pdhStatus != ERROR_SUCCESS) { /* dprintf(D_ALWAYS, "PdhCollectQueryData returns 0x%x\n", (int)pdhStatus); */ exit_status = 4; break; } pdhStatus = PdhGetFormattedCounterValue(hCounterQueueLength, PDH_FMT_LONG, NULL, &counterval); if (pdhStatus != ERROR_SUCCESS) { /* dprintf(D_ALWAYS, "PdhGetFormattedCounterValue returns 0x%x\n", (int)pdhStatus); */ exit_status = 5; break; } queuelen = counterval.longValue; cpuload = 0.0; for (i=0; i < ncpus; i++) { pdhStatus = PdhGetFormattedCounterValue(hCounterCpuLoad[i], PDH_FMT_DOUBLE, NULL, &counterval); if (pdhStatus != ERROR_SUCCESS) { /* dprintf(D_ALWAYS, "PdhGetFormattedCounterValue returns 0x%x\n", (int)pdhStatus); */ exit_status = 6; break; } cpuload += counterval.doubleValue/100.0; } EnterCriticalSection(&cs); /* ** Here is the code to simulate Unix style load average on Win32. ** If the system is not fully utilized, the length of the processor ** queue should be near 0. When the system is fully utilized, ** we must discount two items on the processor queue: the system ** thread and the thread which we displaced to take our measurement. ** If there are more than 2 items on the queue, we want to add this ** to our load average to show the additional load on the system. */ if (queuelen > 2) { samples[nextsample].load = cpuload + queuelen - 2; } else { samples[nextsample].load = cpuload; } samples[nextsample].sampletime = time(NULL); LeaveCriticalSection(&cs); nextsample++; nextsample %= NUM_SAMPLES; Sleep(SAMPLE_INTERVAL); } // we encountered a problem, so clean up everything and exit. for (i=0; i<ncpus;i++) { PdhRemoveCounter(hCounterCpuLoad[i]); } free(hCounterCpuLoad); PdhCloseQuery(hQuery); return exit_status; }
// Get some data periodically. Called once per frame. // As a side-effect, this routine retains the most recently read perf data. // // This code is called once per frame from the main thread. It updates // variables that are read later in the frame from within the graphics system. // Thus, there is no need to make either the read or write code thread-safe. // If this calling pattern is ever changed, make both ends thread-safe. void CPUUsage::UpdatePeriodicData() { LARGE_INTEGER currentTick; // Capture the first value of a tick. QueryPerformanceCounter( ¤tTick ); double tickDiff = ( ( double )( currentTick.QuadPart - m_LastUpdateTick.QuadPart ) ) / ( double )m_Frequency. QuadPart; if( tickDiff < 0 ) { tickDiff = 0; } if( tickDiff < m_secondsPerUpdate ) return; std::vector <void*>::iterator voidIter; if( m_vecProcessorCounters.empty() ) { // In the empty case (can't read counters), just return zeros for CPU percent. for( unsigned int i = 0; i < m_numCounters; i++ ) { m_CPUPercentCounters[i] = 0.0f; } } else { // Get current counter values. int i = 0; for( voidIter = m_vecProcessorCounters.begin(); voidIter != m_vecProcessorCounters.end(); ++voidIter, i++ ) { // Start with a zero, in case there's some error. m_CPUPercentCounters[i] = 0.0f; ProcessorCounter* counterInstance = ( ProcessorCounter* )*voidIter; // Read all current counters via their handles. If some error condition // has left us with a NULL query handle, the call will just fail and we'll // still have a zero counter this time. PDH_STATUS status = PdhCollectQueryData( counterInstance->m_hQuery ); if( status == ERROR_SUCCESS ) { // In rare cases, PdhGetFormattedCounterValue can return bad values (<0 or >100) // when called in this pattern. If that becomes a problem, it's possible to // work around the problem by adding a short sleep (e.g. 10 msec) and a second // call to PdhCollectQueryData, before calling PdhGetFormattedCounterValue. // In testing, we haven't seen the problem. Any such problem that occurs on a // single read will tend to not occur on the next read, so any such problem // is transient enough to ignore. PDH_FMT_COUNTERVALUE value; // Get the actual value out of this counter query. // Just pass a NULL for type, since we already know the type of this value. status = PdhGetFormattedCounterValue( counterInstance->m_hCounter, PDH_FMT_DOUBLE, NULL, &value ); // Make sure we have valid or new data (new also implies valid), and cache it. if( status == ERROR_SUCCESS && ( value.CStatus == PDH_CSTATUS_NEW_DATA || value.CStatus == PDH_CSTATUS_VALID_DATA ) ) { m_CPUPercentCounters[i] = ( double )value.doubleValue; } } } m_LastUpdateTick = currentTick; } }
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; }
bool PerfCounterMuninNodePlugin::OpenCounter() { PDH_STATUS status; m_Name = m_SectionName.substr(strlen(PerfCounterMuninNodePlugin::SectionPrefix)); OSVERSIONINFO osvi; ZeroMemory(&osvi, sizeof(OSVERSIONINFO)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); if (!GetVersionEx(&osvi) || (osvi.dwPlatformId != VER_PLATFORM_WIN32_NT)) { _Module.LogError("PerfCounter plugin: %s: unknown OS or not NT based", m_Name.c_str()); return false; //unknown OS or not NT based } // Create a PDH query status = PdhOpenQuery(NULL, 0, &m_PerfQuery); if (status != ERROR_SUCCESS) { _Module.LogError("PerfCounter plugin: %s: PdhOpenQuery error=%x", m_Name.c_str(), status); return false; } TString objectName = A2TConvert(g_Config.GetValue(m_SectionName, "Object", "LogicalDisk")); TString counterName = A2TConvert(g_Config.GetValue(m_SectionName, "Counter", "% Disk Time")); DWORD counterListLength = 0; DWORD instanceListLength = 0; if (g_Config.GetValueB(m_SectionName, "UseEnglishObjectNames", true)) { counterName = GetPdhCounterLocalizedName(counterName.c_str()); objectName = GetPdhCounterLocalizedName(objectName.c_str()); } status = PdhEnumObjectItems(NULL, NULL, objectName.c_str(), NULL, &counterListLength, NULL, &instanceListLength, PERF_DETAIL_EXPERT, 0); if (status != PDH_MORE_DATA) { _Module.LogError("PerfCounter plugin: %s: PdhEnumObjectItems error=%x", m_Name.c_str(), status); return false; } TCHAR *counterList = new TCHAR[counterListLength+2]; TCHAR *instanceList = new TCHAR[instanceListLength+2]; counterList[0] = NULL; instanceList[0] = NULL; counterList[1] = NULL; instanceList[1] = NULL; status = PdhEnumObjectItems(NULL, NULL, objectName.c_str(), counterList, &counterListLength, instanceList, &instanceListLength, PERF_DETAIL_EXPERT, 0); if (status != ERROR_SUCCESS) { delete [] counterList; delete [] instanceList; _Module.LogError("PerfCounter plugin: %s: PdhEnumObjectItems error=%x", m_Name.c_str(), status); return false; } int pos = 0; TCHAR *instanceName = instanceList; while (instanceName[0] != NULL) { std::string counterInstanceName = T2AConvert(instanceName); m_CounterNames.push_back(counterInstanceName); while (instanceName[0] != NULL) instanceName++; instanceName++; } delete [] counterList; delete [] instanceList; TCHAR counterPath[MAX_PATH] = {0}; HCOUNTER counterHandle; if (!m_CounterNames.empty()) { if (g_Config.GetValueB(m_SectionName, "DropTotal", true)) { assert(m_CounterNames.back().compare("_Total") == 0); // We drop the last instance name as it is _Total m_CounterNames.pop_back(); } for (size_t i = 0; i < m_CounterNames.size(); i++) { TString instanceNameStr = A2TConvert(m_CounterNames[i]); _sntprintf(counterPath, MAX_PATH, _T("\\%s(%s)\\%s"), objectName.c_str(), instanceNameStr.c_str(), counterName.c_str()); // Associate the uptime counter with the query status = PdhAddCounter(m_PerfQuery, counterPath, 0, &counterHandle); if (status != ERROR_SUCCESS) { _Module.LogError("PerfCounter plugin: %s: PDH add counter error=%x", m_Name.c_str(), status); return false; } m_Counters.push_back(counterHandle); } } else { // A counter with a single instance (Uptime for example) m_CounterNames.push_back("0"); _sntprintf(counterPath, MAX_PATH, _T("\\%s\\%s"), objectName.c_str(), counterName.c_str()); // Associate the uptime counter with the query status = PdhAddCounter(m_PerfQuery, counterPath, 0, &counterHandle); if (status != ERROR_SUCCESS) { _Module.LogError("PerfCounter plugin: %s: PDH add counter error=%x", m_Name.c_str(), status); return false; } m_Counters.push_back(counterHandle); } // Collect init data status = PdhCollectQueryData(m_PerfQuery); if (status != ERROR_SUCCESS) { if (status == PDH_INVALID_HANDLE) { _Module.LogError("PerfCounter plugin: %s: PDH collect data: PDH_INVALID_HANDLE", m_Name.c_str()); return false; } if (status == PDH_NO_DATA) { _Module.LogError("PerfCounter plugin: %s: PDH collect data: PDH_NO_DATA", m_Name.c_str()); return false; } _Module.LogError("PerfCounter plugin: %s: PDH collect data error", m_Name.c_str()); return false; } // Setup Counter Format m_dwCounterFormat = PDH_FMT_DOUBLE; std::string counterFormatStr = g_Config.GetValue(m_SectionName, "CounterFormat", "double"); if (!counterFormatStr.compare("double") || !counterFormatStr.compare("float")) { m_dwCounterFormat = PDH_FMT_DOUBLE; } else if (!counterFormatStr.compare("int") || !counterFormatStr.compare("long")) { m_dwCounterFormat = PDH_FMT_LONG; } else if (!counterFormatStr.compare("int64") || !counterFormatStr.compare("longlong") || !counterFormatStr.compare("large")) { m_dwCounterFormat = PDH_FMT_LARGE; } else { _Module.LogError("PerfCounter plugin: %s: Unknown CounterFormat", m_Name.c_str()); assert(!"Unknown CounterFormat!"); } m_CounterMultiply = g_Config.GetValueF(m_SectionName, "CounterMultiply", 1.0); return true; }