Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C++
Article

How to get CPU usage by performance counters (without PDH)

Rate me:
Please Sign up or sign in to vote.
4.60/5 (66 votes)
10 Feb 2005CPOL2 min read 1.7M   17.1K   123   217
Get CPU usage by performance counters without using PDH.dll.

Introduction

The information in this article applies to Windows NT, Win2K/XP. There is no specific Win32 API that retrieves the CPU usage. An undocumented API, NtQuerySystemInformation in ntdll.dll, would help us retrieve the CPU usage. However, CPU usage can be retrieved by using performance counters. Since PDH.dll (Performance Data Helper) is not distributed with the Visual Studio, and not everyone has this file, I decided to do it without the help of PDH.dll.

The CPU usage counter is of type PERF_100NSEC_TIMER_INV which has the following calculation:

100*(1-(X1-X0)/(Y1-Y0))
  X - CounterData
  Y - 100NsTime
  Time base - 100Ns

where the denominator (Y) represents the total elapsed time of the sample interval and the numerator (X) represents the time during the interval when the monitored components were inactive.

My CCpuUsage class has a method called GetCpuUsage which runs through the performance objects and counters and retrieves the CPU usage. Since the CPU usage can be determined by two samplings, the first call to GetCpuUsage() returns 0, and all calls thereafter returns the CPU usage.

Comment

On Windows NT, CPU usage counter is '% Total processor time' whose index is 240 under 'System' object whose index is 2. However, in Win2K/XP, Microsoft moved that counter to '% processor time' whose index is 6 under '_Total' instance of 'Processor' object whose index is 238. Read 'INFO: Percent Total Performance Counter Changes on Windows 2000' (Q259390) in MSDN.

There is no difference between WinNT and Win2K/XP in the performance counters for getting CPU usage for a specific process. The counter '% processor time' whose index is 6 under the object 'Process' whose index is 230.

The Sample

C++
#include "CpuUsage.h"

int main(int argc, char* argv[])
{
    int processID=0;
    CCpuUsage usageA;
    CCpuUsage usageB;
    CCpuUsage usageC;

    printf("SystemWide Cpu Usage     " 
           "Explorer cpu usage       " 
           "Cpu Usage for processID 0\n"); 
    printf("====================     " 
           "==================       "
           "========================\n"); 
    while (true)
    {
        // Display the system-wide cpu usage and the "Explorer" cpu usage

        int SystemWideCpuUsage = usageA.GetCpuUsage();
        int ProcessCpuUsageByName = usageB.GetCpuUsage("explorer");
        int ProcessCpuUsageByID = usageC.GetCpuUsage(processID);
        printf("%19d%%%22d%%%31d%%\r",SystemWideCpuUsage, 
               ProcessCpuUsageByName, ProcessCpuUsageByID);

        Sleep(1000);
    }
    return 0;
}

Updates

  • 6-May-2003 - Fixed bug when looking for an instance. The bug occurred because the instances in the performance counters are in Unicode. Added a sample function to get CPU usage for a specific process.
  • 12-Jun-2003 - Fixed bug in realloc method.
  • 22-Jun-2003 - Defined structure alignment to be 8 (by using #pragma directive). Other sizes cause the function to return 100% CPU usage. (Thanks to Scolver tip.)
  • 12-Feb-2004 - Enabled performance counters of perfOS.dll (which holds processor counters) automatically for Win2K/XP.
  • 20-May-2004 - Retrieving only the specified counter data (instead of retrieving all counters and iterating till finding the specified object) (for more information, refer to OscarTV comments).
  • 03-Jun-2004 - Enabled performance counters of perfProc.dll (which holds process counters) automatically for Win2K/XP.
  • 06-Jun-2004 - Wrapped the code into a class in order to enable getting CPU usage for different processes at the same iteration.
  • 18-Nov-2004 - Extended variable from 8 bytes to 32 bytes.
  • 03-Feb-2005 - Enabled getting performance counters by process ID.
  • 09-Feb-2005 - Returns 0 when the specified process-ID doesn't exist.

More of my articles using performance counters

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Israel Israel
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: Really Like the Code But Problem with % > 100 Pin
Daver20823-May-07 7:51
Daver20823-May-07 7:51 
GeneralMultiple Processors Pin
BiShopx31-Dec-05 12:07
BiShopx31-Dec-05 12:07 
GeneralRe: Multiple Processors Pin
cpp_prgmer11-Sep-06 5:05
cpp_prgmer11-Sep-06 5:05 
Questiongetting disk throughput with CPerfCounters? Pin
T1TAN12-Dec-05 22:53
T1TAN12-Dec-05 22:53 
AnswerRe: getting disk throughput with CPerfCounters? Pin
Dudi Avramov13-Dec-05 5:44
Dudi Avramov13-Dec-05 5:44 
GeneralRe: getting disk throughput with CPerfCounters? Pin
supergoofy12-Feb-06 23:43
supergoofy12-Feb-06 23:43 
GeneralRe: getting disk throughput with CPerfCounters? Pin
LexaPublic15-Jan-07 23:59
LexaPublic15-Jan-07 23:59 
QuestionError compiling the source code Pin
mpbejo29-Oct-05 0:20
mpbejo29-Oct-05 0:20 
Hi Dude,
I am tring to compile your source code under Borland c++ 5 but I have some problems, here the errors that I find:

[Linker Error] Unresolved external '__stdcall _com_util::ConvertStringToBSTR(const char *)' referenced from C:\DOWNLOAD\CPU\CPUUSAGE_SRC\CPUUSAGE.OBJ
[Linker Error] Unresolved external '__stdcall _com_issue_error(long)' referenced from C:\DOWNLOAD\CPU\CPUUSAGE_SRC\CPUUSAGE.OBJ
[Linker Error] Unresolved external '__stdcall _com_util::ConvertBSTRToString(wchar_t *)' referenced from C:\DOWNLOAD\CPU\CPUUSAGE_SRC\CPUUSAGE.OBJ

I hope You or somebody can help me
Thank You very much
Marco

AnswerRe: Error compiling the source code Pin
Dudi Avramov29-Oct-05 22:41
Dudi Avramov29-Oct-05 22:41 
AnswerRe: Error compiling the source code Pin
Artur_ABC29-Jun-06 4:55
Artur_ABC29-Jun-06 4:55 
GeneralWindows CE support Pin
ronannaughton25-Oct-05 15:50
ronannaughton25-Oct-05 15:50 
GeneralRe: Windows CE support Pin
chiru_tati29-May-08 22:32
chiru_tati29-May-08 22:32 
Generalas he would be indice of: Pin
hormigatroy5-Sep-05 4:26
hormigatroy5-Sep-05 4:26 
GeneralWin 98/ME Pin
johnny2pints15-Jul-05 7:58
johnny2pints15-Jul-05 7:58 
GeneralRe: Win 98/ME Pin
Dudi Avramov17-Jul-05 1:09
Dudi Avramov17-Jul-05 1:09 
GeneralVery Useful Work Pin
Pescador17-Jun-05 12:25
Pescador17-Jun-05 12:25 
GeneralRe: Very Useful Work Pin
Pescador20-Jun-05 6:23
Pescador20-Jun-05 6:23 
GeneralRe: Very Useful Work Pin
Dudi Avramov27-Jun-05 1:19
Dudi Avramov27-Jun-05 1:19 
GeneralModifying System Counter Values Pin
Rene Pally24-May-05 10:38
Rene Pally24-May-05 10:38 
GeneralRe: Modifying System Counter Values Pin
Dudi Avramov28-May-05 20:46
Dudi Avramov28-May-05 20:46 
GeneralCpuUsage more than 100 Pin
3m2u20-May-05 17:23
3m2u20-May-05 17:23 
GeneralRe: CpuUsage more than 100 Pin
DaosMistique24-Dec-05 12:29
DaosMistique24-Dec-05 12:29 
QuestionHow to find process memory Pin
Member 163732321-Apr-05 16:19
Member 163732321-Apr-05 16:19 
AnswerRe: How to find process memory Pin
Dudi Avramov24-Apr-05 9:38
Dudi Avramov24-Apr-05 9:38 
GeneralRe: How to find process memory Pin
Anonymous28-Apr-05 17:15
Anonymous28-Apr-05 17:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.