5,666,979 members and growing! (15,664 online)
Email Password   helpLost your password?
General Reading » Hardware & System » General     Intermediate License: The Code Project Open License (CPOL)

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

By Dudi Avramov

Get CPU usage by performance counters without using PDH.dll.
VC6, C++Windows, NT4, Win2K, WinXPVS6, Visual Studio, Dev

Posted: 22 Dec 2002
Updated: 10 Feb 2005
Views: 239,874
Bookmarked: 80 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
54 votes for this Article.
Popularity: 7.19 Rating: 4.15 out of 5
2 votes, 3.7%
1
2 votes, 3.7%
2
5 votes, 9.3%
3
10 votes, 18.5%
4
35 votes, 64.8%
5

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

#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)

About the Author

Dudi Avramov



Occupation: Web Developer
Location: Israel Israel

Other popular Hardware & System articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 209 (Total in Forum: 209) (Refresh)FirstPrevNext
GeneralThe dll was crashed when conducting Stress TestmemberArsenal_Lee1:06 31 Oct '08  
Questioncpu usage when there are more then one corememberVadim Winebrand0:13 8 Jul '08  
GeneralDoesn't work on VistamemberVitalyTomilov5:45 6 Jun '08  
QuestionCan I use same code on WinPE?membersam3270:05 17 Apr '08  
GeneralRefactor ?memberSwinefeaster15:05 18 Mar '08  
GeneralExe works fine on Win 2003 server. But under ISAPI it doesn't?memberSukar8:19 3 Oct '07  
Generaluser time, kernel time index...memberpulse_3:02 27 Sep '07  
Question=100%memberru-ikari-kun6:56 9 Aug '07  
GeneralDoes this code work in Vista?memberDezo10:11 3 Aug '07  
GeneralRe: Does this code work in Vista?memberDudi Avramov23:30 7 Aug '07  
GeneralRe: Does this code work in Vista?memberHoward Anderson6:15 14 Dec '07  
GeneralRe: Does this code work in Vista?memberSwinefeaster14:41 18 Mar '08  
Generalhow to get the CPU usage data using Turbo C++?memberKhathar1:55 28 Apr '07  
GeneralGccmemberAenema22:46 20 Feb '07  
GeneralI may be retardedmemberobyman6:43 7 Sep '06  
GeneralRe: I may be retardedmemberDudi Avramov5:02 10 Sep '06  
GeneralRe: I may be retardedmemberobyman1:53 11 Sep '06  
GeneralRe: I may be retardedmemberru-ikari-kun1:16 14 Aug '07  
GeneralIt won't compile -memberRaven Caelladore11:39 2 Jul '06  
GeneralRe: It won't compile -memberRaven Caelladore4:23 6 Jul '06  
GeneralRe: It won't compile -membermadhav_sigdel0:45 13 Oct '07  
General[problem] only return 0 in threadmemberopenkwang23:43 1 May '06  
GeneralReally Like the Code But Problem with % > 100memberchris1754:03 10 Apr '06  
GeneralRe: Really Like the Code But Problem with % > 100memberDudi Avramov21:38 10 Apr '06  
GeneralRe: Really Like the Code But Problem with % > 100memberDaver2088:51 23 May '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 10 Feb 2005
Editor: Chris Maunder
Copyright 2002 by Dudi Avramov
Everything else Copyright © CodeProject, 1999-2008
Web10 | Advertise on the Code Project