Performance Monitor - Get System Counter Values (CPU, Memory, etc.)

Environment: VC6, Windows 2000, Windows NT 4.0 SP3

Note: This article is specific to Windows 2000 and Windows NT 4.0 SP3+. It does not support Windows 95 or 98. For Windows NT 4, you will need PDH.DLL and PDH.LIB which are not supplied with the OS.

I wrote this code because I couldn't find any good resource meters for Windows 2000. Plenty of them exist for Windows 95/98 and I figured that I might as well write my own.

I have wrapped the PDH into a nice C++ class called CPerfMon. It will support all the counters available under Windows. I have done some predefined timers for easy use. These are as follows:

// % of cpu in use
#define CNTR_CPU "\\Processor(_Total)\\% Processor Time" 

// mem in use measured in bytes
#define CNTR_MEMINUSE_BYTES "\\Memory\\Committed Bytes" 

// mem available measured in bytes
#define CNTR_MEMAVAIL_BYTES "\\Memory\\Available Bytes" 

// mem avail in kilobytes
#define CNTR_MEMAVAIL_KB "\\Memory\\Available KBytes" 

// mem avail in megabytes
#define CNTR_MEMAVAIL_MB "\\Memory\\Available MBytes" 

// % of mem in use
#define CNTR_MEMINUSE_PERCENT "\\Memory\\% Committed Bytes In Use" 

// commit limit on memory in bytes
#define CNTR_MEMLIMIT_BYTES "\\Memory\\Commit Limit" 

This class contains a few easy to use functions to add counters, remove counters, get statistics (avg, min, max), and to get the current value. On to the code. :)

First you need to initialize the class:

CPerfMon pm;

// init
if (!pm.Initialize())
{
 AfxMessageBox("PerfMon did not initialize properly!");
 return;
}
Then we add the counters we want to track. To find new counter names, use the function PdhBrowseCounters().
int nCpuIndex = pm.AddCounter(CNTR_CPU); // we used a predefined name for these counters...
int nMemIndex = pm.AddCounter(CNTR_MEMINUSE_PERCENT);

// test them if you want
ASSERT(nCpuIndex > -1 && nMemIndex > -1);
Then we can call the functions to obtain values:
// execute the query for our counters
if (!pm.CollectQueryData())
{
 AfxMessageBox("Could not collect data.");
 return;
}

// grab the current value for our counters
long lCpu = pm.GetCounterValue(nCpuIndex);
long lMem = pm.GetCounterValue(nMemIndex);

// -999 is returned on error (hacky I know. Sorry.) ;)
ASSERT(lCpu != -999L && lMem != -999L); 

// grab the statistical values
long lCpuMin, lCpuMax, lCpuAvg;
long lMemMin, lMemMax, lMemAvg;
if (!pm.GetStatistics(&lCpuMin, &lCpuMax, &lCpuAvg, nCpuIndex) 
|| !pm.GetStatistics(&lMemMin, &lMemMax, &lMemAvg, nMemIndex))
{
 AfxMessageBox("Could not get statistical data.");
 return;
}
Now all the values that you want are contained in lCpu, lMem, lCpuMin, lCpuMax, lCpuAvg, lMemMin, lMemMax, and lMemAvg.

The way the class was intended to work is with a window timer. Set a timer called every 1/2 second or second and call the above functions. Then populate your dialog or whatever with the returned data. See the demo for an example of this.

Good luck and have fun. Please feel free to email me any comments or questions (or post them to CodeGuru).

Downloads

Download demo project - 15 Kb
Download source - 4 Kb


Comments

  • Nike Wind Max+instagram, desire you contain the color to step on your feet!

    Posted by madytreathy on 04/24/2013 06:42am

    Remember in 2008, if not earlier, when Nike launched on of the separated shoe color projects, the war cry "Bound Your Colours", "Nike PhotoiD" layout, [url=http://markwarren.org.uk/goodbuy.cfm]nike free run uk[/url] effect has not been as enthusiastic as expected. Think, 2008 Canon IXUS 80 IS Digital greetings card arcade but one 8 million pixels, Nokia, the plastic phone retail is the at worst regulation, NikeiD was promote to color in the photos as a basis someone is concerned sneakers excise color, although gripping, but does bother some. Instagram which sort this item make sport and modest, Nike PHOTOiD homeopathic upgrade customization services, recently [url=http://markwarren.org.uk/property-waet.cfm]air max 90[/url] released a unique plan. That such iD can you implement pictures as instagram account shoe color, little while put up Nike Air Max shoes and Nike Puff Max 1, Nike Affectedness Max 90 953 options. Interested in children's shoes, you [url=http://markwarren.org.uk/goodbuy.cfm]nike free run[/url] can every vanish into thin air's valid website photoid.Nike.com, in reckoning to flick through other people's creative sweat, or you can make an effort to upload your own instagram photo, base your own Nike Mood Max.

    Reply
  • Process enumeration of Remote Machines

    Posted by Legacy on 01/18/2004 12:00am

    Originally posted by: kiran napit

    How do i enumerate processes of remote machines using PDH functions.

    Reply
  • Performance Monitor - Get System Counter Values (CPU, Memory, etc.)

    Posted by Legacy on 07/10/2003 12:00am

    Originally posted by: BadJake

    Demo won't compile because of missing afxres.h

    • Performance Monitor - Get System Counter Values (CPU, Memory, etc.)

      Posted by Rajenda1 on 07/31/2008 03:10am

      You need to include the mfc path in the include path. mfc folder contain afxres.h file. mfc folder in inside include folder.

      Reply
    • ee

      Posted by tina2000 on 05/14/2005 01:43am

      ee

      Reply
    Reply
  • Access Violation In Debugging mode

    Posted by Legacy on 07/04/2003 12:00am

    Originally posted by: jeans

    Your source code is running fine when it is not in the debugging mode. I'm using Microsoft VC++ 6.0 with latest SP, Windows 2000 Pro. When I running in debugging mode and trace it, it will encountered a lot of access violation in Ntdll.dll.

    Reply
  • counter names

    Posted by Legacy on 04/06/2003 12:00am

    Originally posted by: Ed

    For all non-English systesm, you need to translate each counte name into OS-native langauge. You can run perfmon.exe to see what counter names are.

    Reply
  • a problem

    Posted by Legacy on 11/11/2002 12:00am

    Originally posted by: Alexander Kolev

    The idea about this class is very cool.But i have a problem when compile with 2 bytes Struct member alignment.Can you help me ..please..

    Reply
  • For russian Win2000

    Posted by Legacy on 05/03/2002 12:00am

    Originally posted by: Sergey_X

    Do not work for russian Win2000? help pls!!!!
    PdhAddCounter retrive the message - PDH_CSTATUS_NO_OBJECT - The specified counter was not found

    Reply
  • Connecting to Remote Machines

    Posted by Legacy on 05/02/2002 12:00am

    Originally posted by: John Wesley

    Is there a function to connect to a remote machine?

    Reply
  • App hangs upon exit

    Posted by Legacy on 04/10/2002 12:00am

    Originally posted by: Greg Holt

    Anyone else tried this with XP? When I run this app, or any app that uses the PDH library, the app always hangs when exiting. Any suggestions?

    Reply
  • system monitoring for windows98

    Posted by Legacy on 02/20/2002 12:00am

    Originally posted by: swapan

    please suggest me , away foe monitoring the system , with windows 98 as tht OS

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • In support of their business continuity and disaster recovery plans, many midsized companies endeavor to avoid putting all their eggs in one basket. Understanding the critical role of last-mile connectivity and always available Internet access for their enterprises, savvy firms utilize redundant connections from multiple service providers. Despite the good intentions, their Internet connectivity risk may still be in a single basket. That is because internet service providers (ISPs) and competitive local …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds