We help IT Professionals succeed at work.

Windows 7 C++ CPU & memory load

thready
thready asked
on
Hi Experts,

I need a little function that will give me the percentage CPU and the percentage memory and return false if

BOOL IsServerLoadWithinAcceptableThresholds(int nMaxCPUPercent=75, int nMaxMemoryPercent=95);

Open in new window


Can anyone help with this?
Thank you!
Mike
Comment
Watch Question

Top Expert 2012
Commented:
The CPU load can be quite straightfoward, see http://www.codeproject.com/Articles/3413/How-to-get-CPU-usage-by-performance-counters-witho ("How to get CPU usage by performance counters"), memory usage is a bit more tricky, but you can do that like

#include <pdh.h>

    PDH_STATUS  status;
    HQUERY        perfQuery = NULL;
    HCOUNTER    hVirtPeakBytesCounter;
    char        acVirtPeakBytesCounterPath[MAX_PATH] = "\\\\.\\Process(*)\\VirtualBytesPeak"; // '*' means all processes, you can use a PID as well
    PDH_FMT_COUNTERVALUE VirtualBytesPeak;
    uint64 ullVirtualBytesPeak;

    //.......................
    //
    // Create a PDH query
    //
    if( PdhOpenQuery(NULL, 0, perfQuery ) != ERROR_SUCCESS )
        return FALSE;

    //
    // Associate the counter with the query
    //
    status = PdhAddCounter(perfQuery, acVirtPeakBytesCounterPath,
                            0, &VirtualBytesPeak );
    if( status != ERROR_SUCCESS )
        return FALSE;


    status = PdhCollectQueryData( perfQuery );
    if( status != ERROR_SUCCESS )
        return FALSE;

    //
    // Get the formatted counter value
    //

    status = PdhGetFormattedCounterValue( VirtualBytesPeak,
                    PDH_FMT_LARGE , NULL, &ullVirtualBytesPeak );
    if( status != ERROR_SUCCESS )
        return FALSE;

    //
    // Close the query
    //
    PdhCloseQuery( &perfQuery );

Open in new window


But why 'tricky' and why using process objects? Well, see yourself: https://technet.microsoft.com/en-us/library/cc778082%28v=ws.10%29.aspx?f=255&MSPPError=-2147217396 ("Memory Object")

Oh, and the amount of physical memory is available via 'GetSystemInfo()' (https://msdn.microsoft.com/en-us/library/windows/desktop/ms724381%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396)

Author

Commented:
Thanks jkr!
Have a great weekend!