Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Task Manager process CPU usage?

Task Manager process CPU usage?

Scheduled Pinned Locked Moved C / C++ / MFC
questionperformancetutorial
8 Posts 2 Posters 9 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • P Offline
    P Offline
    Peter Sjostrom
    wrote on last edited by
    #1

    Hi, I know how to use the PSI.DLL (was it?) for checking a process' memory usage etc. But how can I get information about each process' CPU usage? I want to include a CPU usage bar in my software to display how much CPU that software is using. Hints anyone?

    B 1 Reply Last reply
    0
    • P Peter Sjostrom

      Hi, I know how to use the PSI.DLL (was it?) for checking a process' memory usage etc. But how can I get information about each process' CPU usage? I want to include a CPU usage bar in my software to display how much CPU that software is using. Hints anyone?

      B Offline
      B Offline
      Bill Wilson
      wrote on last edited by
      #2

      WMI provides that information. I don't remember the specific profider. something like WIN32_Process. There are some examples of exactly what you are trying to do. I saw them while looking for some other WMI code. Just do some searches on google, code guru etc. You'll find them. Hope this helps, Bill

      P 1 Reply Last reply
      0
      • B Bill Wilson

        WMI provides that information. I don't remember the specific profider. something like WIN32_Process. There are some examples of exactly what you are trying to do. I saw them while looking for some other WMI code. Just do some searches on google, code guru etc. You'll find them. Hope this helps, Bill

        P Offline
        P Offline
        Peter Sjostrom
        wrote on last edited by
        #3

        I managed to find PDH.DLL which uses either WMI or Registry data. I can get CPU usage from here, MSDN also contains docs on this DLL. Only problem now is I can't understand how to get process CPU usage, which functions, do I use Counters etc, how do I set them up? An example would be perfect. :-)

        B 1 Reply Last reply
        0
        • P Peter Sjostrom

          I managed to find PDH.DLL which uses either WMI or Registry data. I can get CPU usage from here, MSDN also contains docs on this DLL. Only problem now is I can't understand how to get process CPU usage, which functions, do I use Counters etc, how do I set them up? An example would be perfect. :-)

          B Offline
          B Offline
          Bill Wilson
          wrote on last edited by
          #4

          I don't know which method your asking about... With WMI, get all instances of Win_32_Processor provider and query the LoadPercentage. This will return an average over 1 second. Here is the class I ended up using in my project utilizing the PDH.dll. I create an instance of the class for each cpu on the system, query each and take an average, when I want to know the answer. Class definition:

          #ifndef __CPUUSAGE_CLASS__
          #define __CPUUSAGE_CLASS__
          #include

          class CCPUUsage {
          public:
          CCPUUsage();
          ~CCPUUsage();
          #pragma message("CCPUUsage")
          BOOL Init(LONG nMinTicksBetweenSamples = 1000, int iProcessor = 0);

          int GetUsage(PBOOL pfNewSample = NULL);
          

          private:
          HQUERY m_hQuery;
          HCOUNTER m_hCounter;
          int m_nMinTicksBetweenSamples;
          DWORD m_msLastTick;
          int m_nLastSampledCPUUsage;
          };

          #endif // __CPUUSAGE_CLASS__

          Class implementation: CCPUUsage::CCPUUsage() { } CCPUUsage::~CCPUUsage() { PdhCloseQuery(m_hQuery); } BOOL CCPUUsage::Init(LONG nMinTicksBetweenSamples, int iProcessor) { m_nMinTicksBetweenSamples = nMinTicksBetweenSamples; m_msLastTick = 0; // m_msLastTick = GetTickCount(); PDH_STATUS pdhs = PdhOpenQuery(NULL, 0, &m_hQuery); CString csPath; csPath.Format("\\Processor(%d)\\%% processor time", iProcessor); pdhs = PdhAddCounter(m_hQuery, TEXT(csPath), 0, &m_hCounter); CString strDiag; strDiag.Format("CCPUUsage::Init, pdhs = %x, Processor = %d",pdhs,iProcessor); TRACEX(strDiag); m_nLastSampledCPUUsage = 0; return (pdhs == 0); } int CCPUUsage::GetUsage(PBOOL pfNewSample ) { BOOL fNewSample; if (pfNewSample == NULL) pfNewSample = &fNewSample; *pfNewSample = FALSE; DWORD msCurrentTick = GetTickCount(); DWORD msLastTick = m_msLastTick; if (msCurrentTick < msLastTick) { // Wrap around, always sample *pfNewSample = TRUE; } else { if ((msLastTick + m_nMinTicksBetweenSamples) < msCurrentTick) { // It's been long since the last sample, get a new sample *pfNewSample = TRUE; } } CString szdiag; if (*pfNewSample) { if ((DWORD) InterlockedExchange((PLONG) &m_msLastTick, msCurrentTick) == msLastTick) { PdhCollectQueryData(m_hQuery); PDH_FMT_COUNTERVALUE pdhfcv; PDH_STATUS stat = PdhGetFormattedCounterValue(m_hCounter, PDH_FMT_LONG, NULL, &pdhfcv); szdiag.Format("GetStatus::PdhGetFormattedCounterValue return

          P 2 Replies Last reply
          0
          • B Bill Wilson

            I don't know which method your asking about... With WMI, get all instances of Win_32_Processor provider and query the LoadPercentage. This will return an average over 1 second. Here is the class I ended up using in my project utilizing the PDH.dll. I create an instance of the class for each cpu on the system, query each and take an average, when I want to know the answer. Class definition:

            #ifndef __CPUUSAGE_CLASS__
            #define __CPUUSAGE_CLASS__
            #include

            class CCPUUsage {
            public:
            CCPUUsage();
            ~CCPUUsage();
            #pragma message("CCPUUsage")
            BOOL Init(LONG nMinTicksBetweenSamples = 1000, int iProcessor = 0);

            int GetUsage(PBOOL pfNewSample = NULL);
            

            private:
            HQUERY m_hQuery;
            HCOUNTER m_hCounter;
            int m_nMinTicksBetweenSamples;
            DWORD m_msLastTick;
            int m_nLastSampledCPUUsage;
            };

            #endif // __CPUUSAGE_CLASS__

            Class implementation: CCPUUsage::CCPUUsage() { } CCPUUsage::~CCPUUsage() { PdhCloseQuery(m_hQuery); } BOOL CCPUUsage::Init(LONG nMinTicksBetweenSamples, int iProcessor) { m_nMinTicksBetweenSamples = nMinTicksBetweenSamples; m_msLastTick = 0; // m_msLastTick = GetTickCount(); PDH_STATUS pdhs = PdhOpenQuery(NULL, 0, &m_hQuery); CString csPath; csPath.Format("\\Processor(%d)\\%% processor time", iProcessor); pdhs = PdhAddCounter(m_hQuery, TEXT(csPath), 0, &m_hCounter); CString strDiag; strDiag.Format("CCPUUsage::Init, pdhs = %x, Processor = %d",pdhs,iProcessor); TRACEX(strDiag); m_nLastSampledCPUUsage = 0; return (pdhs == 0); } int CCPUUsage::GetUsage(PBOOL pfNewSample ) { BOOL fNewSample; if (pfNewSample == NULL) pfNewSample = &fNewSample; *pfNewSample = FALSE; DWORD msCurrentTick = GetTickCount(); DWORD msLastTick = m_msLastTick; if (msCurrentTick < msLastTick) { // Wrap around, always sample *pfNewSample = TRUE; } else { if ((msLastTick + m_nMinTicksBetweenSamples) < msCurrentTick) { // It's been long since the last sample, get a new sample *pfNewSample = TRUE; } } CString szdiag; if (*pfNewSample) { if ((DWORD) InterlockedExchange((PLONG) &m_msLastTick, msCurrentTick) == msLastTick) { PdhCollectQueryData(m_hQuery); PDH_FMT_COUNTERVALUE pdhfcv; PDH_STATUS stat = PdhGetFormattedCounterValue(m_hCounter, PDH_FMT_LONG, NULL, &pdhfcv); szdiag.Format("GetStatus::PdhGetFormattedCounterValue return

            P Offline
            P Offline
            Peter Sjostrom
            wrote on last edited by
            #5

            Well, thanks, it helps to get started on CPU Usage, but it's not what I want. What I want is to measure the CPU Usage for my specific process. I want to know how much CPU my own software is taking, the software that this code is going to go into. I want to know if my software starts to grab 90+ % of the CPU, if it does it's an error situation and action needs to be taken. Task Manager can obviously do it, but I am unable to find out how to do. I'm reading the PDH docs on MSDN, but it's a bit over my head and I thought someone had done it, or maybe the Task Manager code is available somewhere?

            B 1 Reply Last reply
            0
            • P Peter Sjostrom

              Well, thanks, it helps to get started on CPU Usage, but it's not what I want. What I want is to measure the CPU Usage for my specific process. I want to know how much CPU my own software is taking, the software that this code is going to go into. I want to know if my software starts to grab 90+ % of the CPU, if it does it's an error situation and action needs to be taken. Task Manager can obviously do it, but I am unable to find out how to do. I'm reading the PDH docs on MSDN, but it's a bit over my head and I thought someone had done it, or maybe the Task Manager code is available somewhere?

              B Offline
              B Offline
              Bill Wilson
              wrote on last edited by
              #6

              Here's the WMI code I used for Overall CPU usage. I believe, that by changing the query to use a different provider, you can get the info you want. I've seen an example that enumerates processes and gets info about them. In any case this class is hard won knowledge and may help.

              // SysInfo.h : Declaration of the CSysInfo

              #ifndef __SYSINFO_H_
              #define __SYSINFO_H_

              #include "resource.h" // main symbols
              #include
              #include

              /////////////////////////////////////////////////////////////////////////////
              // CSysInfo
              class ATL_NO_VTABLE CSysInfo :
              public CComObjectRootEx,
              public IDispatchImpl,
              public CComControl,
              public IPersistStreamInitImpl,
              public IOleControlImpl,
              public IOleObjectImpl,
              public IOleInPlaceActiveObjectImpl,
              public IViewObjectExImpl,
              public IOleInPlaceObjectWindowlessImpl,
              public ISupportErrorInfo,
              public CComCoClass
              {
              public:
              CSysInfo()
              {
              m_pUnkMarshaler = NULL;

              }
              
              
              ~CSysInfo();
              

              DECLARE_GET_CONTROLLING_UNKNOWN()
              DECLARE_REGISTRY_RESOURCEID(IDR_SYSINFO)

              DECLARE_PROTECT_FINAL_CONSTRUCT()

              BEGIN_COM_MAP(CSysInfo)
              COM_INTERFACE_ENTRY(ISysInfo)
              COM_INTERFACE_ENTRY(IDispatch)
              COM_INTERFACE_ENTRY(IViewObjectEx)
              COM_INTERFACE_ENTRY(IViewObject2)
              COM_INTERFACE_ENTRY(IViewObject)
              COM_INTERFACE_ENTRY(IOleInPlaceObjectWindowless)
              COM_INTERFACE_ENTRY(IOleInPlaceObject)
              COM_INTERFACE_ENTRY2(IOleWindow, IOleInPlaceObjectWindowless)
              COM_INTERFACE_ENTRY(IOleInPlaceActiveObject)
              COM_INTERFACE_ENTRY(IOleControl)
              COM_INTERFACE_ENTRY(IOleObject)
              COM_INTERFACE_ENTRY(IPersistStreamInit)
              COM_INTERFACE_ENTRY2(IPersist, IPersistStreamInit)
              COM_INTERFACE_ENTRY(ISupportErrorInfo)
              COM_INTERFACE_ENTRY_AGGREGATE(IID_IMarshal, m_pUnkMarshaler.p)
              END_COM_MAP()

              BEGIN_PROP_MAP(CSysInfo)
              PROP_DATA_ENTRY("_cx", m_sizeExtent.cx, VT_UI4)
              PROP_DATA_ENTRY("_cy", m_sizeExtent.cy, VT_UI4)
              // Example entries
              // PROP_ENTRY("Property Description", dispid, clsid)
              // PROP_PAGE(CLSID_StockColorPage)
              END_PROP_MAP()

              BEGIN_MSG_MAP(CSysInfo)
              CHAIN_MSG_MAP(CComControl)
              DEFAULT_REFLECTION_HANDLER()
              END_MSG_MAP()
              // Handler prototypes:
              // LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
              // LRESULT CommandHandler(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled);
              // LRESULT NotifyHandler(int id

              P 1 Reply Last reply
              0
              • B Bill Wilson

                I don't know which method your asking about... With WMI, get all instances of Win_32_Processor provider and query the LoadPercentage. This will return an average over 1 second. Here is the class I ended up using in my project utilizing the PDH.dll. I create an instance of the class for each cpu on the system, query each and take an average, when I want to know the answer. Class definition:

                #ifndef __CPUUSAGE_CLASS__
                #define __CPUUSAGE_CLASS__
                #include

                class CCPUUsage {
                public:
                CCPUUsage();
                ~CCPUUsage();
                #pragma message("CCPUUsage")
                BOOL Init(LONG nMinTicksBetweenSamples = 1000, int iProcessor = 0);

                int GetUsage(PBOOL pfNewSample = NULL);
                

                private:
                HQUERY m_hQuery;
                HCOUNTER m_hCounter;
                int m_nMinTicksBetweenSamples;
                DWORD m_msLastTick;
                int m_nLastSampledCPUUsage;
                };

                #endif // __CPUUSAGE_CLASS__

                Class implementation: CCPUUsage::CCPUUsage() { } CCPUUsage::~CCPUUsage() { PdhCloseQuery(m_hQuery); } BOOL CCPUUsage::Init(LONG nMinTicksBetweenSamples, int iProcessor) { m_nMinTicksBetweenSamples = nMinTicksBetweenSamples; m_msLastTick = 0; // m_msLastTick = GetTickCount(); PDH_STATUS pdhs = PdhOpenQuery(NULL, 0, &m_hQuery); CString csPath; csPath.Format("\\Processor(%d)\\%% processor time", iProcessor); pdhs = PdhAddCounter(m_hQuery, TEXT(csPath), 0, &m_hCounter); CString strDiag; strDiag.Format("CCPUUsage::Init, pdhs = %x, Processor = %d",pdhs,iProcessor); TRACEX(strDiag); m_nLastSampledCPUUsage = 0; return (pdhs == 0); } int CCPUUsage::GetUsage(PBOOL pfNewSample ) { BOOL fNewSample; if (pfNewSample == NULL) pfNewSample = &fNewSample; *pfNewSample = FALSE; DWORD msCurrentTick = GetTickCount(); DWORD msLastTick = m_msLastTick; if (msCurrentTick < msLastTick) { // Wrap around, always sample *pfNewSample = TRUE; } else { if ((msLastTick + m_nMinTicksBetweenSamples) < msCurrentTick) { // It's been long since the last sample, get a new sample *pfNewSample = TRUE; } } CString szdiag; if (*pfNewSample) { if ((DWORD) InterlockedExchange((PLONG) &m_msLastTick, msCurrentTick) == msLastTick) { PdhCollectQueryData(m_hQuery); PDH_FMT_COUNTERVALUE pdhfcv; PDH_STATUS stat = PdhGetFormattedCounterValue(m_hCounter, PDH_FMT_LONG, NULL, &pdhfcv); szdiag.Format("GetStatus::PdhGetFormattedCounterValue return

                P Offline
                P Offline
                Peter Sjostrom
                wrote on last edited by
                #7

                Ok, some guesswork and trial and error... First, as with another article I found on the net, the processor time parameter is Windows language dependant: csPath.Format("\\Processor(%d)\\%% processor time", iProcessor); changes into: csPath.Format("\\Processor(%d)\\%% processortid", iProcessor); ...to work on my Swedish Windows. I don't know how to find this for any language yet. To find the CPU Usage for a specific process use: csPath.Format("\\Process(%s)\\%% processortid", sProcess); for example: csPath.Format("\\Process(iexplore)\\%% processortid"); for Internet Explorer CPU usage. This does what I want now, except for that language dependency which I must solve now... (anyone know?)

                1 Reply Last reply
                0
                • B Bill Wilson

                  Here's the WMI code I used for Overall CPU usage. I believe, that by changing the query to use a different provider, you can get the info you want. I've seen an example that enumerates processes and gets info about them. In any case this class is hard won knowledge and may help.

                  // SysInfo.h : Declaration of the CSysInfo

                  #ifndef __SYSINFO_H_
                  #define __SYSINFO_H_

                  #include "resource.h" // main symbols
                  #include
                  #include

                  /////////////////////////////////////////////////////////////////////////////
                  // CSysInfo
                  class ATL_NO_VTABLE CSysInfo :
                  public CComObjectRootEx,
                  public IDispatchImpl,
                  public CComControl,
                  public IPersistStreamInitImpl,
                  public IOleControlImpl,
                  public IOleObjectImpl,
                  public IOleInPlaceActiveObjectImpl,
                  public IViewObjectExImpl,
                  public IOleInPlaceObjectWindowlessImpl,
                  public ISupportErrorInfo,
                  public CComCoClass
                  {
                  public:
                  CSysInfo()
                  {
                  m_pUnkMarshaler = NULL;

                  }
                  
                  
                  ~CSysInfo();
                  

                  DECLARE_GET_CONTROLLING_UNKNOWN()
                  DECLARE_REGISTRY_RESOURCEID(IDR_SYSINFO)

                  DECLARE_PROTECT_FINAL_CONSTRUCT()

                  BEGIN_COM_MAP(CSysInfo)
                  COM_INTERFACE_ENTRY(ISysInfo)
                  COM_INTERFACE_ENTRY(IDispatch)
                  COM_INTERFACE_ENTRY(IViewObjectEx)
                  COM_INTERFACE_ENTRY(IViewObject2)
                  COM_INTERFACE_ENTRY(IViewObject)
                  COM_INTERFACE_ENTRY(IOleInPlaceObjectWindowless)
                  COM_INTERFACE_ENTRY(IOleInPlaceObject)
                  COM_INTERFACE_ENTRY2(IOleWindow, IOleInPlaceObjectWindowless)
                  COM_INTERFACE_ENTRY(IOleInPlaceActiveObject)
                  COM_INTERFACE_ENTRY(IOleControl)
                  COM_INTERFACE_ENTRY(IOleObject)
                  COM_INTERFACE_ENTRY(IPersistStreamInit)
                  COM_INTERFACE_ENTRY2(IPersist, IPersistStreamInit)
                  COM_INTERFACE_ENTRY(ISupportErrorInfo)
                  COM_INTERFACE_ENTRY_AGGREGATE(IID_IMarshal, m_pUnkMarshaler.p)
                  END_COM_MAP()

                  BEGIN_PROP_MAP(CSysInfo)
                  PROP_DATA_ENTRY("_cx", m_sizeExtent.cx, VT_UI4)
                  PROP_DATA_ENTRY("_cy", m_sizeExtent.cy, VT_UI4)
                  // Example entries
                  // PROP_ENTRY("Property Description", dispid, clsid)
                  // PROP_PAGE(CLSID_StockColorPage)
                  END_PROP_MAP()

                  BEGIN_MSG_MAP(CSysInfo)
                  CHAIN_MSG_MAP(CComControl)
                  DEFAULT_REFLECTION_HANDLER()
                  END_MSG_MAP()
                  // Handler prototypes:
                  // LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
                  // LRESULT CommandHandler(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled);
                  // LRESULT NotifyHandler(int id

                  P Offline
                  P Offline
                  Peter Sjostrom
                  wrote on last edited by
                  #8

                  Oops, thanks a lot! I will digest this in upcoming days :omg:

                  1 Reply Last reply
                  0
                  Reply
                  • Reply as topic
                  Log in to reply
                  • Oldest to Newest
                  • Newest to Oldest
                  • Most Votes


                  • Login

                  • Don't have an account? Register

                  • Login or register to search.
                  • First post
                    Last post
                  0
                  • Categories
                  • Recent
                  • Tags
                  • Popular
                  • World
                  • Users
                  • Groups