2

如何在 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

4

2 回答 2

2

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

SYSTEM_INFO systemInfo;

GetSystemInfo( &systemInfo );
numberofCPU = systemInfo.dwNumberOfProcessors;
于 2016-06-20T16:08:29.640 回答
1

C++ 作为一种语言不提供特性来确定这一点。编译器只生成执行要求的代码。

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

不过,您可以进行间接测量。我建议您同时在多个线程上运行您的场景(并在每个线程上重复多次)并测量每个线程消耗的天文时间。如果您将在任务管理器中监控 CPU/内存/IO 消耗并将此信息与线程花费的平均时间进行比较,您可以估算出您的场景实际“成本”。

还有一方面。您的结果将只是一个估计,这取决于您的 Windows 机器的实际配置(域成员与否)等,CoInitializeSecurity取决于各种安全设置和调用它的帐户类型。盒子上有很多选项,在域中如何配置安全性。但是,即使不是很可靠的估计也总比没有好。

于 2016-01-20T08:54:26.790 回答