The Coder
The Coder

Reputation: 143

How to determine CPU consumption in C++ per core

How can I get the CPU load per core (quadcore cpu with hyperthreading), in C++? I am looking for a result like in the task manager in %.

I am trying to do it now like this: The problem is the code recognizes 9 cores (i have 8 :/)

#define _WIN32_DCOM
#include <iostream>
#include <comdef.h>
#include <Wbemidl.h>

# pragma comment(lib, "wbemuuid.lib")
using namespace std;
bool getCpuLoadInfo() {
HRESULT hres;

// Step 1: --------------------------------------------------
// Initialize COM. ------------------------------------------

hres = CoInitializeEx(0, COINIT_MULTITHREADED);
if (FAILED(hres)) {
    cout << "Failed to initialize COM library. Error code = 0x" << hex << hres << endl;
    return 0;                  // Program has failed.
}

// Step 2: --------------------------------------------------
// Set general COM security levels --------------------------
// Note: If you are using Windows 2000, you need to specify -
// the default authentication credentials for a user by using
// a SOLE_AUTHENTICATION_LIST structure in the pAuthList ----
// parameter of CoInitializeSecurity ------------------------

hres = CoInitializeSecurity(
    NULL,
    -1,                          // COM authentication
    NULL,                        // Authentication services
    NULL,                        // Reserved
    RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication
    RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation  
    NULL,                        // Authentication info
    EOAC_NONE,                   // Additional capabilities
    NULL                         // Reserved
    );


if (FAILED(hres)) {
    cout << "Failed to initialize security. Error code = 0x"
        << hex << hres << endl;
    CoUninitialize();
    return 0;                    // Program has failed.
}

// Step 3: ---------------------------------------------------
// Obtain the initial locator to WMI -------------------------

IWbemLocator *pLoc = NULL;

hres = CoCreateInstance(
    CLSID_WbemLocator,
    0,
    CLSCTX_INPROC_SERVER,
    IID_IWbemLocator, (LPVOID *)&pLoc);

if (FAILED(hres)) {
    cout << "Failed to create IWbemLocator object."
        << " Err code = 0x"
        << hex << hres << endl;
    CoUninitialize();
    return 0;                 // Program has failed.
}

// Step 4: -----------------------------------------------------
// Connect to WMI through the IWbemLocator::ConnectServer method

IWbemServices *pSvc = NULL;

// Connect to the root\cimv2 namespace with
// the current user and obtain pointer pSvc
// to make IWbemServices calls.
hres = pLoc->ConnectServer(
    _bstr_t(L"ROOT\\CIMV2"), // Object path of WMI namespace
    NULL,                    // User name. NULL = current user
    NULL,                    // User password. NULL = current
    0,                       // Locale. NULL indicates current
    NULL,                    // Security flags.
    0,                       // Authority (e.g. Kerberos)
    0,                       // Context object
    &pSvc                    // pointer to IWbemServices proxy
    );

if (FAILED(hres)) {
    cout << "Could not connect. Error code = 0x" << hex << hres << endl;
    pLoc->Release();
    CoUninitialize();
    return 0;                // Program has failed.
}

cout << "Connected to ROOT\\CIMV2 WMI namespace" << endl;


// Step 5: --------------------------------------------------
// Set security levels on the proxy -------------------------

hres = CoSetProxyBlanket(
    pSvc,                        // Indicates the proxy to set
    RPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxx
    RPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxx
    NULL,                        // Server principal name
    RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx
    RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
    NULL,                        // client identity
    EOAC_NONE                    // proxy capabilities
    );

if (FAILED(hres)) {
    cout << "Could not set proxy blanket. Error code = 0x"
        << hex << hres << endl;
    pSvc->Release();
    pLoc->Release();
    CoUninitialize();
    return 0;               // Program has failed.
}

// Step 6: --------------------------------------------------
// Use the IWbemServices pointer to make requests of WMI ----

// For example, get the name of the operating system
IEnumWbemClassObject* pEnumerator = NULL;
IWbemClassObject *pclsObj;
int i;
while (1) {
    i = 1;
    hres = pSvc->ExecQuery(
        bstr_t("WQL"),
        bstr_t("SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor"),

        WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
        NULL,
        &pEnumerator);

    if (FAILED(hres)) {
        cout << "Query for operating system name failed."
            << " Error code = 0x"
            << hex << hres << endl;
        pSvc->Release();
        pLoc->Release();
        CoUninitialize();
        return 0;               // Program has failed.
    }

    // Step 7: -------------------------------------------------
    // Get the data from the query in step 6 -------------------


    ULONG uReturn = 0;

    while (pEnumerator) {
        HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,
            &pclsObj, &uReturn);

        if (0 == uReturn) {
            break;
        }

        VARIANT vtProp;

        // Get the value of the Name property
        //hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
        hr = pclsObj->Get(L"PercentProcessorTime", 0, &vtProp, 0, 0);
        wcout << " CPU Usage of CPU " << i << " : " << vtProp.bstrVal << endl;
        VariantClear(&vtProp);

        //IMPORTANT!!
        pclsObj->Release();

        i++;
    }

}

// Cleanup
// ========

pSvc->Release();
pLoc->Release();
pEnumerator->Release();
pclsObj->Release();
CoUninitialize();

return 0;   // Program successfully completed.
}

Is there an other (maybe more easy) way to get the cpu load per core in %? Or am I on the right track but something is wrong with my code? If so what is wrong with it? :P

Upvotes: 2

Views: 2310

Answers (2)

SaraV
SaraV

Reputation: 21

The last number is the value of _Total and that's why you see 9 cores instead of 8, you can show the results based on number of cores. For retrieving number of cores, use the following command:

SYSTEM_INFO systemInfo;

GetSystemInfo( &systemInfo );
numberofCPU = systemInfo.dwNumberOfProcessors;

Upvotes: 2

Kirill Kobelev
Kirill Kobelev

Reputation: 10557

C++ as a language does not provide features to determine this. Compiler just generates code that is doing what is asked for.

Other aspect. Your scenario is widely using features of the operating system that involve processing in different processes and in kernel. Most likely you want to know the sum of all activities and not just how much CPU cycles your particular process consumed.

Nevertheless you can make indirect measurements. I would recommend you to run your scenario on several threads at the same time (and repeat it many times on each thread) and measure the astronomical time consumed by each thread. If you will monitor CPU/Memory/IO consumption in the task manager and compare this info with average time spent by threads, you can get an estimate of what does your scenario actually "cost".

There is one more aspect. Your result will be just an estimate that will depend on actual configuration of your Windows box (member of a domain or not), etc. CoInitializeSecurity depends on various security settings and type of account that is calling it. There are tons of options on the box and in the domain how to configure security. But still, even not very reliable estimate is better than nothing.

Upvotes: 1

Related Questions