struct VM_SYSINFO_CPULOAD *vm_sys_info_create_cpu_data(void) {
  int i = 0;
  HQUERY tmpq = 0;
  struct VM_SYSINFO_CPULOAD *dbuf = NULL;
  dbuf = (struct VM_SYSINFO_CPULOAD *)malloc(sizeof(struct VM_SYSINFO_CPULOAD));
  if (dbuf != NULL) {
    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) {
      free(dbuf);
      dbuf = NULL;
      } else {
          dbuf[0].tickspassed = 0;
          // prepare system specific fields
          dbuf[0].CpuLoadQuery = 0;
          for( i = 0; i < MAX_PERF_PARAMETERS; ++i )
            dbuf[0].CpuPerfCounters[i] = NULL;
          tmpq = dbuf[0].CpuLoadQuery;
          PdhOpenQuery(NULL, 0, &tmpq);
          if (tmpq == 0) {
            free(dbuf[0].cpudes);
            free(dbuf);
            dbuf = NULL;
            } else 
                dbuf[0].CpuLoadQuery = tmpq;
          }
    }
  return dbuf;
  }
Exemplo n.º 2
0
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;
}
Exemplo n.º 3
0
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;
}
Exemplo n.º 4
0
/* Must be called before any values can be read. This creates all the 
 * necessary PDH values
 */
int sg_win32_start_capture()
{
#ifdef WIN32
	PDH_STATUS pdh_status;

	if(is_started) {
		return -1;
	}

	pdh_status = PdhOpenQuery(NULL, 0, &h_query);

	if(pdh_status != ERROR_SUCCESS) {
		char *mess = NULL;
		if(pdh_status == PDH_INVALID_ARGUMENT)
			mess = "Invalid argument o.O";
		else if(pdh_status == PDH_MEMORY_ALLOCATION_FAILURE)
			mess = "Memory allocation failure";
		sg_set_error(SG_ERROR_PDHOPEN, mess);
		return -1;
	}
	if (add_all_monitors() == -1) {
		return -1;
	}

	is_started = 1;
#endif
	return 0;
}
Exemplo n.º 5
0
// Function name	: CPerfMon::Initialize
// Description	    : Initialize the query and memory
// Return type		: BOOL ; true on success; false on fail
//
// R E V I S I O N S:
// DATE       PROGRAMMER      CHANGES
//
BOOL CPerfMon::Initialize()
{
	if (PdhOpenQuery(NULL, 1, &m_hQuery) != ERROR_SUCCESS)
		return false;

	return true;
}
Exemplo n.º 6
0
JNIEXPORT jboolean JNICALL Java_jp_co_acroquest_endosnipe_javelin_resource_proc_PerfCounter_openQuery
  (JNIEnv *env, jobject obj) {
	if ( PdhOpenQuery(NULL, 0, &hQuery) == ERROR_SUCCESS )
  	{
		return true;
	}
	return false;
}
Exemplo n.º 7
0
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);
}
Exemplo n.º 8
0
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);
}
Exemplo n.º 9
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;
	}
}
Exemplo n.º 10
0
JNIEXPORT jlong JNICALL Java_org_hyperic_hq_plugin_mssql_PDH_pdhOpenQuery(JNIEnv *env, jclass jc) {
    HQUERY     h_query;
    PDH_STATUS status;

    status = PdhOpenQuery(NULL, 0, &h_query);
    if (status != ERROR_SUCCESS) {
        plugin_throw_exception(env, get_error_message(status));
        return 0;
    }
    return (jlong)h_query;
}
Exemplo n.º 11
0
JNIEXPORT jint JNICALL Java_org_krakenapps_winapi_PerformanceCounter_open(JNIEnv *env, jobject obj) {
	PDH_HQUERY phQuery = NULL;
	PDH_STATUS stat = 0;

	stat = PdhOpenQuery(NULL, 0, &phQuery);
	if(stat != ERROR_SUCCESS) {
		fprintf(stderr, "Error in PdhOpenQuery: 0x%x\n", stat);
		return 0;
	}

	return (jint)phQuery;
}
Exemplo n.º 12
0
Arquivo: Cpu.cpp Projeto: Elbe2/Gundby
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;
}
Exemplo n.º 13
0
PDH_STATUS	zbx_PdhOpenQuery(const char *function, PDH_HQUERY query)
{
    PDH_STATUS	pdh_status;

    if (ERROR_SUCCESS != (pdh_status = PdhOpenQuery(NULL, 0, query)))
    {
        zabbix_log(LOG_LEVEL_ERR, "%s(): call to PdhOpenQuery() failed: %s",
                   function, strerror_from_module(pdh_status, L"PDH.DLL"));
    }

    return pdh_status;
}
Exemplo n.º 14
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;
}
Exemplo n.º 15
0
Arquivo: pdh.c Projeto: 40a/sigar
JNIEXPORT jlong JNICALL SIGAR_JNI(win32_Pdh_pdhOpenQuery)
(JNIEnv *env, jobject cur)
{
    HQUERY     h_query;
    PDH_STATUS status;

    status = PdhOpenQuery(NULL, 0, &h_query);
    if (status != ERROR_SUCCESS) {
        win32_throw_exception(env, get_error_message(status));
        return 0;
    }
    return (jlong)h_query;
}
Exemplo n.º 16
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);
}
Exemplo n.º 18
0
/**
 * 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.
 * Windows Resource Monitor reports cached as Standby+Modified this is not the
 * equivalent of Linux file system cache, however it could be viewed as
 * analagous memory usage, and it makes sense to retain some consistency with
 * Windows tools.
 * Windows Resource Monitor reports free memory as free and zero page list bytes,
 * this is used for free memory. There are no obvious equivalents for shared
 * and buffers so these counters are reported as unknown.
 * 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->swap_total = memStat.ullTotalPageFile;
	mem->swap_free = memStat.ullAvailPageFile;
	PDH_HQUERY query;
	if (PdhOpenQuery(NULL, 0, &query) == ERROR_SUCCESS) {
		PDH_HCOUNTER free, standbyCore, standbyNormal, standbyReserve, modified, pageIn, pageOut;
		if (addCounterToQuery(MEM_COUNTER_OBJECT, NULL, MEM_COUNTER_FREE, &query, &free) == ERROR_SUCCESS &&
			addCounterToQuery(MEM_COUNTER_OBJECT, NULL, MEM_COUNTER_STANDBY_CORE, &query, &standbyCore) == ERROR_SUCCESS &&
			addCounterToQuery(MEM_COUNTER_OBJECT, NULL, MEM_COUNTER_STANDBY_NORMAL, &query, &standbyNormal) == ERROR_SUCCESS &&
			addCounterToQuery(MEM_COUNTER_OBJECT, NULL, MEM_COUNTER_STANDBY_RESERVE, &query, &standbyReserve) == ERROR_SUCCESS &&
			addCounterToQuery(MEM_COUNTER_OBJECT, NULL, MEM_COUNTER_MODIFIED, &query, &modified) == 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_free = getRawCounterValue(&free);
			mem->mem_cached = getRawCounterValue(&standbyCore) +
				getRawCounterValue(&standbyNormal) +
				getRawCounterValue(&standbyReserve) +
				getRawCounterValue(&modified);
			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_GAUGE_64;
	mem->mem_buffers = UNKNOWN_GAUGE_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;
}
Exemplo n.º 19
0
void CSystemInfo::GetWinSystemInfo()
{
	HQUERY	hQuery = NULL ;
	char   szPathBuffer[MAX_PATH];

	if( PdhOpenQuery(NULL, NULL, &hQuery) != ERROR_SUCCESS )
		return ;

	ZeroMemory(szPathBuffer, sizeof(szPathBuffer));

	PDH_FMT_COUNTERVALUE  fmtValue;

	//CPU使用率
//	strcpy(szPathBuffer, "\\Processor(_Total)\\% Processor Time");
	strcpy(szPathBuffer, "\\Processor(0)\\% Processor Time");
	if( GetSysItemInfo(hQuery, szPathBuffer,  PDH_FMT_LONG, fmtValue) )
	{
		nCPU = fmtValue.longValue ;
	}

	//进程数
	strcpy(szPathBuffer, "\\System\\Processes");
	if( GetSysItemInfo(hQuery, szPathBuffer,  PDH_FMT_LONG, fmtValue) )
	{
		nProcessNumber = fmtValue.longValue;
	}

	//线程数
	strcpy(szPathBuffer, "\\System\\Threads");
	if( GetSysItemInfo(hQuery, szPathBuffer,  PDH_FMT_LONG, fmtValue) )
	{
		nThreadNumber =fmtValue.longValue;
	}

	strcpy(szPathBuffer, "\\Memory\\Commit Limit");
	if( GetSysItemInfo(hQuery, szPathBuffer,  PDH_FMT_LONG, fmtValue) )
	{
		nMemoryTotal =fmtValue.longValue;
	}

	strcpy(szPathBuffer, "\\Memory\\Committed Bytes");
	if( GetSysItemInfo(hQuery, szPathBuffer,  PDH_FMT_LONG, fmtValue) )
	{
		nUserMemory =fmtValue.longValue;
	}

	PdhCloseQuery(hQuery);
}
Exemplo n.º 20
0
/**
 * If we are going to collect counters every second while we work out whether
 * we've got 64bit or not, lets just make the counter query once and reuse it.
 */
static PDH_STATUS createCounterQuery()
{
	PDH_STATUS status= PdhOpenQuery(NULL, 0, &query);
	if (status == ERROR_SUCCESS) {
		addCounter(NIO_COUNTER_BYTES_IN, &bytesIn);
		addCounter(NIO_COUNTER_PACKETS_IN, &pktsIn);
		addCounter(NIO_COUNTER_ERRORS_IN, &errorsIn);
		addCounter(NIO_COUNTER_DISCARDS_IN, &discardsIn);
		addCounter(NIO_COUNTER_BYTES_OUT, &bytesOut);
		addCounter(NIO_COUNTER_PACKETS_OUT, &pktsOut);
		addCounter(NIO_COUNTER_ERRORS_OUT, &errorsOut);
		addCounter(NIO_COUNTER_DISCARDS_OUT, &discardsOut);
		return ERROR_SUCCESS;
	} else {
		return status;
	}
}
Exemplo n.º 21
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;
}
Exemplo n.º 22
0
    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 );
        }
    }
Exemplo n.º 23
0
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;
}
Exemplo n.º 24
0
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;
}
Exemplo n.º 25
0
/**
 * @brief
 *	opens profile .
 *
 * @param[in] prof - pointer to PDH_profile struct
 *
 * @return	BOOL
 * @retval	TRUE	success
 * @retval	FALSE	error
 *
 */
static BOOL
open_profile(PDH_profile *prof)
{
	BOOL ret = TRUE;

	__try {

		if (PdhOpenQuery(NULL, 0, &(prof->hQuery)) != ERROR_SUCCESS) {
			prof->hQuery = NULL;
			ret = FALSE;
		}
	}
	__except(EXCEPTION_EXECUTE_HANDLER) {
		ret = FALSE;
	}

	return (ret);
}
Exemplo n.º 26
0
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;
}
Exemplo n.º 27
0
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;
}
Exemplo n.º 28
0
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;
}
Exemplo n.º 29
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;
}
Exemplo n.º 30
0
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;
}