如何确定每个C ++的C ++ CPU消耗

时间:2016-01-20 01:25:39

标签: c++ windows winapi multicore cpu-load

如何在C ++中获得每个内核的CPU负载(具有超线程的四核cpu)? 我在%。的任务管理器中寻找结果。

我现在正试着这样做: 问题是代码识别9个核心(我有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.
}

是否有其他(可能更简单)的方法来获得每个核心的CPU负载%? 或者我是在正确的轨道上,但我的代码有问题? 如果是这样有什么问题呢? :P

2 个答案:

答案 0 :(得分:1)

C ++作为一种语言不提供确定此功能的功能。编译器只生成正在执行要求的代码。

其他方面。您的方案广泛使用操作系统的功能,涉及在不同进程和内核中进行处理。您很可能想知道所有活动的总和,而不仅仅是您的特定流程消耗了多少CPU周期。

然而,您可以进行间接测量。我建议你同时在几个线程上运行你的场景(并在每个线程上重复多次)并测量每个线程消耗的天文时间。如果您将监视任务管理器中的CPU /内存/ IO消耗并将此信息与线程所花费的平均时间进行比较,则可以估计您的方案实际上“花费”了什么。

还有一个方面。您的结果只是一个估计值,取决于您的Windows框的实际配置(域的成员与否)等。CoInitializeSecurity取决于各种安全设置和调用它的帐户类型。框中和域中有大量选项如何配置安全性。但是,即使不是非常可靠的估计总比没有好。

答案 1 :(得分:1)

最后一个数字是_Total的值,这就是为什么你看到9个内核而不是8个内核,你可以根据内核数量显示结果。要检索核心数,请使用以下命令:

SYSTEM_INFO systemInfo;

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