Windows Azure Cloud Storage ermöglicht es Ihnen bereits ab 0,10€ pro GB/Monat die Vorteile der Cloud zu nutzen.
Hypercell ein ] Hypercell aus ] Zeige Navigation ] Verstecke Navigation ]
c++.de  
   
Advanced Developers Conference     
Bücher-Shop mit Amazon (Buchkategorien)C++ : Referenzen zu C++ : C++ Builder : Visual C++ : C# : Java : Spieleprogrammierung : Systemprogrammierung Linux : Software-Entwicklung : .NET : Compilertechnik : Algorithmen & Datenstrukturen : Objektorientierung : Entwurfsmuster : UML : eXtreme Programming : Scrum : Projektmanagement : Software-Testing : Datenbanken : Tom DeMarco : Dilbert : User Friendly
C/C++ Forum :: FAQ - WinAPI ::  CPU Auslastung bei DualCore CPU's einzeln Auslesen?     Zeige alle Beiträge auf einer Seite Auf Beitrag antworten
Autor Nachricht
pmneo
Mitglied

Benutzerprofil
Anmeldungsdatum: 21.06.2006
Beiträge: 17
Beitrag pmneo Mitglied 19:42:56 18.11.2006   Titel:   CPU Auslastung bei DualCore CPU's einzeln Auslesen?            Zitieren

Hi!

Ich möchte gerne die CPU Auslastung auslesen!

Ich hab dazu diesen Code gefunden:

C/C++ Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
// using undocumented functions and structures

#define
SystemBasicInformation        0
#define
    SystemPerformanceInformation    2
#define
SystemTimeInformation        3

#define
Li2Double(x)    ((double)((x).HighPart) * 4.294967296E9 + (double)((x).LowPart))

typedef struct
{
    DWORD    dwUnknown1;
    ULONG    uKeMaximumIncrement;
    ULONG    uPageSize;
    ULONG    uMmNumberOfPhysicalPages;
    ULONG    uMmLowestPhysicalPage;
    ULONG    UMmHighestPhysicalPage;
    ULONG    uAllocationGranularity;
    PVOID    pLowestUserAddress;
    PVOID    pMmHighestUserAddress;
    ULONG    uKeActiveProcessors;
    BYTE    bKeNumberProcessors;
    BYTE    bUnknown2;
    WORD    bUnknown3;
} SYSTEM_BASIC_INFORMATION;

typedef struct
{
    LARGE_INTEGER    liIdleTime;
    DWORD        dwSpare[76];
} SYSTEM_PERFORMANCE_INFORMATION;

typedef struct
{
    LARGE_INTEGER    liKeBootTime;
    LARGE_INTEGER    liKeSystemTime;
    LARGE_INTEGER    liExpTimeZoneBias;
    ULONG            uCurrentTimeZoneID;
    DWORD            dwReserved;
} SYSTEM_TIME_INFORMATION;

// NtQuerySystemInformation
// The function copies the system information of the specified type into a buffer
// NTSYSAPI
// NTSTATUS
// NTAPI
// NtQuerySystemInformation(
//        IN UINT SystemInformationClass,        // information type
//        OUT PVOID SystemInformation,        // pointer to buffer
//        IN ULONG SystemInformationLength,    // buffer size in bytes
//        OUT PULONG ReturnLength OPTIONAL    // pointer to a 32 bit variable that
//                                            // receives the number of bytes written
//                                            // to the buffer
// );


typedef LONG (WINAPI *PROCNTQSI) (UINT, PVOID, ULONG, PULONG);

// this functions return the CPU usage of one second using
// undocumented Windows NT API's
// this code will not run on Win 9x

double GetCPUUsages()
{
    SYSTEM_BASIC_INFORMATION        SysBaseInfo;
    SYSTEM_TIME_INFORMATION            SysTimeInfo;
    SYSTEM_PERFORMANCE_INFORMATION    SysPerfInfo;
    LONG                            status;
    LARGE_INTEGER                    liOldIdleTime = {0, 0};
    LARGE_INTEGER                    liOldSystemTime = {0, 0};
    double                            dbIdleTime;
    double                            dbSystemTime;
    PROCNTQSI                        NtQuerySystemInformation;

    NtQuerySystemInformation = (PROCNTQSI)GetProcAddress(GetModuleHandle(_T("ntdll")),
        "NtQuerySystemInformation");

    if (NtQuerySystemInformation)
    {
        status = NtQuerySystemInformation(SystemBasicInformation, &SysBaseInfo,
            sizeof(SysBaseInfo), NULL);

        if (status == NO_ERROR)
        {
            // get system time
            status = NtQuerySystemInformation(SystemTimeInformation, &SysTimeInfo,
                sizeof(SysTimeInfo), NULL);

            if (status == NO_ERROR)
            {
                // get system idle time
                status = NtQuerySystemInformation(SystemPerformanceInformation,
                    &SysPerfInfo, sizeof(SysPerfInfo), NULL);

                if (status == NO_ERROR)
                {
                    liOldIdleTime = SysPerfInfo.liIdleTime;
                    liOldSystemTime = SysTimeInfo.liKeSystemTime;

                    // wait one second
                    ::Sleep(1000);

                    // get new System time
                    status = NtQuerySystemInformation(SystemTimeInformation, &SysTimeInfo,
                        sizeof(SysTimeInfo), NULL);

                    if (status == NO_ERROR)
                    {
                        // get new system idle time

                        status = NtQuerySystemInformation(SystemPerformanceInformation,
                            &SysPerfInfo, sizeof(SysPerfInfo), NULL);

                        if (status == NO_ERROR)
                        {
                            // current value = new value - old value
                            dbIdleTime = Li2Double(SysPerfInfo.liIdleTime) - Li2Double(liOldIdleTime);
                            dbSystemTime = Li2Double(SysTimeInfo.liKeSystemTime) - Li2Double(liOldSystemTime);

                            // currentCpuIdle = IdleTime / SystemTime;
                            dbIdleTime = dbIdleTime / dbSystemTime;

                            // currentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors
                            dbIdleTime = 100.0 - dbIdleTime * 100.0 / (double)SysBaseInfo.bKeNumberProcessors + 0.5;
                        }
                    }
                }
            }
        }
    }

    return dbIdleTime;
}
C/C++ Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
// using undocumented functions and structures

#define
SystemBasicInformation 0
#define
SystemPerformanceInformation 2
#define
SystemTimeInformation 3

#define
Li2Double(x) ((double)((x).HighPart) * 4.294967296E9 + (double)((x).LowPart))

typedef struct
{
DWORD dwUnknown1;
ULONG uKeMaximumIncrement;
ULONG uPageSize;
ULONG uMmNumberOfPhysicalPages;
ULONG uMmLowestPhysicalPage;
ULONG UMmHighestPhysicalPage;
ULONG uAllocationGranularity;
PVOID pLowestUserAddress;
PVOID pMmHighestUserAddress;
ULONG uKeActiveProcessors;
BYTE bKeNumberProcessors;
BYTE bUnknown2;
WORD bUnknown3;
} SYSTEM_BASIC_INFORMATION;

typedef struct
{
LARGE_INTEGER liIdleTime;
DWORD dwSpare[76];
} SYSTEM_PERFORMANCE_INFORMATION;

typedef struct
{
LARGE_INTEGER liKeBootTime;
LARGE_INTEGER liKeSystemTime;
LARGE_INTEGER liExpTimeZoneBias;
ULONG uCurrentTimeZoneID;
DWORD dwReserved;
} SYSTEM_TIME_INFORMATION;

// NtQuerySystemInformation
// The function copies the system information of the specified type into a buffer
// NTSYSAPI
// NTSTATUS
// NTAPI
// NtQuerySystemInformation(
// IN UINT SystemInformationClass, // information type
// OUT PVOID SystemInformation, // pointer to buffer
// IN ULONG SystemInformationLength, // buffer size in bytes
// OUT PULONG ReturnLength OPTIONAL // pointer to a 32 bit variable that
// // receives the number of bytes written
// // to the buffer
// );


typedef LONG (WINAPI *PROCNTQSI) (UINT, PVOID, ULONG, PULONG);

// this functions return the CPU usage of one second using
// undocumented Windows NT API's
// this code will not run on Win 9x

double GetCPUUsages()
{
SYSTEM_BASIC_INFORMATION SysBaseInfo;
SYSTEM_TIME_INFORMATION SysTimeInfo;
SYSTEM_PERFORMANCE_INFORMATION SysPerfInfo;
LONG status;
LARGE_INTEGER liOldIdleTime = {0, 0};
LARGE_INTEGER liOldSystemTime = {0, 0};
double dbIdleTime;
double dbSystemTime;
PROCNTQSI NtQuerySystemInformation;

NtQuerySystemInformation = (PROCNTQSI)GetProcAddress(GetModuleHandle(_T("ntdll")),
"NtQuerySystemInformation");

if (NtQuerySystemInformation)
{
status = NtQuerySystemInformation(SystemBasicInformation, &SysBaseInfo,
sizeof(SysBaseInfo), NULL);

if (status == NO_ERROR)
{
// get system time
status = NtQuerySystemInformation(SystemTimeInformation, &SysTimeInfo,
sizeof(SysTimeInfo), NULL);

if (status == NO_ERROR)
{
// get system idle time
status = NtQuerySystemInformation(SystemPerformanceInformation,
&SysPerfInfo, sizeof(SysPerfInfo), NULL);

if (status == NO_ERROR)
{
liOldIdleTime = SysPerfInfo.liIdleTime;
liOldSystemTime = SysTimeInfo.liKeSystemTime;

// wait one second
::Sleep(1000);

// get new System time
status = NtQuerySystemInformation(SystemTimeInformation, &SysTimeInfo,
sizeof(SysTimeInfo), NULL);

if (status == NO_ERROR)
{
// get new system idle time

status = NtQuerySystemInformation(SystemPerformanceInformation,
&SysPerfInfo, sizeof(SysPerfInfo), NULL);

if (status == NO_ERROR)
{
// current value = new value - old value
dbIdleTime = Li2Double(SysPerfInfo.liIdleTime) - Li2Double(liOldIdleTime);
dbSystemTime = Li2Double(SysTimeInfo.liKeSystemTime) - Li2Double(liOldSystemTime);

// currentCpuIdle = IdleTime / SystemTime;
dbIdleTime = dbIdleTime / dbSystemTime;

// currentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors
dbIdleTime = 100.0 - dbIdleTime * 100.0 / (double)SysBaseInfo.bKeNumberProcessors + 0.5;
}
}
}
}
}
}

return dbIdleTime;
}
C/C++ Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
// using undocumented functions and structures

#define
SystemBasicInformation        0
#define
    SystemPerformanceInformation    2
#define
SystemTimeInformation        3

#define
Li2Double(x)    ((double)((x).HighPart) * 4.294967296E9 + (double)((x).LowPart))

typedef struct
{
    DWORD    dwUnknown1;
    ULONG    uKeMaximumIncrement;
    ULONG    uPageSize;
    ULONG    uMmNumberOfPhysicalPages;
    ULONG    uMmLowestPhysicalPage;
    ULONG    UMmHighestPhysicalPage;
    ULONG    uAllocationGranularity;
    PVOID    pLowestUserAddress;
    PVOID    pMmHighestUserAddress;
    ULONG    uKeActiveProcessors;
    BYTE    bKeNumberProcessors;
    BYTE    bUnknown2;
    WORD    bUnknown3;
} SYSTEM_BASIC_INFORMATION;

typedef struct
{
    LARGE_INTEGER    liIdleTime;
    DWORD        dwSpare[76];
} SYSTEM_PERFORMANCE_INFORMATION;

typedef struct
{
    LARGE_INTEGER    liKeBootTime;
    LARGE_INTEGER    liKeSystemTime;
    LARGE_INTEGER    liExpTimeZoneBias;
    ULONG            uCurrentTimeZoneID;
    DWORD            dwReserved;
} SYSTEM_TIME_INFORMATION;

// NtQuerySystemInformation
// The function copies the system information of the specified type into a buffer
// NTSYSAPI
// NTSTATUS
// NTAPI
// NtQuerySystemInformation(
//        IN UINT SystemInformationClass,        // information type
//        OUT PVOID SystemInformation,        // pointer to buffer
//        IN ULONG SystemInformationLength,    // buffer size in bytes
//        OUT PULONG ReturnLength OPTIONAL    // pointer to a 32 bit variable that
//                                            // receives the number of bytes written
//                                            // to the buffer
// );


typedef LONG (WINAPI *PROCNTQSI) (UINT, PVOID, ULONG, PULONG);

// this functions return the CPU usage of one second using
// undocumented Windows NT API's
// this code will not run on Win 9x

double GetCPUUsages()
{
    SYSTEM_BASIC_INFORMATION        SysBaseInfo;
    SYSTEM_TIME_INFORMATION            SysTimeInfo;
    SYSTEM_PERFORMANCE_INFORMATION    SysPerfInfo;
    LONG                            status;
    LARGE_INTEGER                    liOldIdleTime = {0, 0};
    LARGE_INTEGER                    liOldSystemTime = {0, 0};
    double                            dbIdleTime;
    double                            dbSystemTime;
    PROCNTQSI                        NtQuerySystemInformation;

    NtQuerySystemInformation = (PROCNTQSI)GetProcAddress(GetModuleHandle(_T("ntdll")),
        "NtQuerySystemInformation");

    if (NtQuerySystemInformation)
    {
        status = NtQuerySystemInformation(SystemBasicInformation, &SysBaseInfo,
            sizeof(SysBaseInfo), NULL);

        if (status == NO_ERROR)
        {
            // get system time
            status = NtQuerySystemInformation(SystemTimeInformation, &SysTimeInfo,
                sizeof(SysTimeInfo), NULL);

            if (status == NO_ERROR)
            {
                // get system idle time
                status = NtQuerySystemInformation(SystemPerformanceInformation,
                    &SysPerfInfo, sizeof(SysPerfInfo), NULL);

                if (status == NO_ERROR)
                {
                    liOldIdleTime = SysPerfInfo.liIdleTime;
                    liOldSystemTime = SysTimeInfo.liKeSystemTime;

                    // wait one second
                    ::Sleep(1000);

                    // get new System time
                    status = NtQuerySystemInformation(SystemTimeInformation, &SysTimeInfo,
                        sizeof(SysTimeInfo), NULL);

                    if (status == NO_ERROR)
                    {
                        // get new system idle time

                        status = NtQuerySystemInformation(SystemPerformanceInformation,
                            &SysPerfInfo, sizeof(SysPerfInfo), NULL);

                        if (status == NO_ERROR)
                        {
                            // current value = new value - old value
                            dbIdleTime = Li2Double(SysPerfInfo.liIdleTime) - Li2Double(liOldIdleTime);
                            dbSystemTime = Li2Double(SysTimeInfo.liKeSystemTime) - Li2Double(liOldSystemTime);

                            // currentCpuIdle = IdleTime / SystemTime;
                            dbIdleTime = dbIdleTime / dbSystemTime;

                            // currentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors
                            dbIdleTime = 100.0 - dbIdleTime * 100.0 / (double)SysBaseInfo.bKeNumberProcessors + 0.5;
                        }
                    }
                }
            }
        }
    }

    return dbIdleTime;
}


Das Funktioniert soweit ja auch ...

Jedoch bekomme ich hier nur ein gesamt Ergebnis!

Ich hätte aber gern die Auslastung Pro CPU Core ...

Ich Arbeite mit VS2005!

Vielleicht kann mir ja jemand helfen?

Bei Code Project hab ich diesen Artikel hier gefunden:

Getting cpu usage in a Multiprocessor Machine

Leider bekomme ich wenn ich es mit VC2005 kompilier keine Werte :(

Vielleicht hat es ja hier schon mal jmd gemacht :D

Gruß & Danke schon mal

pmneo
Werbeunterbrechung
pmneo
Mitglied

Benutzerprofil
Anmeldungsdatum: 21.06.2006
Beiträge: 17
Beitrag pmneo Mitglied 01:16:30 19.11.2006   Titel:              Zitieren

Tja dann beantworte ich meine Frage eben selbst :D

So Funkiontiert es:

C/C++ Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
// wmi_test.cpp : Definiert den Einstiegspunkt für die Konsolenanwendung.
//


#include
"stdafx.h"
#define
_WIN32_DCOM
#include
<iostream>
using namespace std;
#include
<comdef.h>
#include
<Wbemidl.h>

# pragma
comment(lib, "wbemuuid.lib")

int doit()
{
    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 1;                  // 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 1;                    // 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 1;                 // 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 1;                // 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 1;               // 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 1;               // 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);
        i++;
    }

    }

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

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

    return 0;   // Program successfully completed.
}

int main(int argc, char **argv)
{
    doit();

    Sleep(10000);
}
C/C++ Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
// wmi_test.cpp : Definiert den Einstiegspunkt für die Konsolenanwendung.
//


#include
"stdafx.h"
#define
_WIN32_DCOM
#include
<iostream>
using namespace std;
#include
<comdef.h>
#include
<Wbemidl.h>

# pragma
comment(lib, "wbemuuid.lib")

int doit()
{
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 1; // 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 1; // 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 1; // 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 1; // 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 1; // 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 1; // 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);
i++;
}

}

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


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

return 0; // Program successfully completed.
}

int main(int argc, char **argv)
{
doit();

Sleep(10000);
}
C/C++ Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
// wmi_test.cpp : Definiert den Einstiegspunkt für die Konsolenanwendung.
//


#include
"stdafx.h"
#define
_WIN32_DCOM
#include
<iostream>
using namespace std;
#include
<comdef.h>
#include
<Wbemidl.h>

# pragma
comment(lib, "wbemuuid.lib")

int doit()
{
    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 1;                  // 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 1;                    // 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 1;                 // 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 1;                // 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 1;               // 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 1;               // 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);
        i++;
    }

    }

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

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

    return 0;   // Program successfully completed.
}

int main(int argc, char **argv)
{
    doit();

    Sleep(10000);
}


Eigentlich genau so wie das von Codeproject, nur das in der Select abfrage nicht von Win32_PerfRawData_PerfOS_Processor sondern von Win32_PerfFormattedData_PerfOS_Processor abgefragt werden muss!

Gruß pmneo ... BTW das wär doch was für die FAQ?? :D
Jochen Kalmbach
Moderator

Benutzerprofil
Anmeldungsdatum: 11.11.2005
Beiträge: 11311
Beitrag Jochen Kalmbach Moderator 09:19:11 19.11.2006   Titel:              Zitieren

Aber eher was für die WinAPI-FAQ ;)

_________________
Greetings
Jochen
(Microsoft MVP VC++) My blog about Win32 and .NET: http://blog.kalmbach-software.de/ (deutsch)
pmneo
Mitglied

Benutzerprofil
Anmeldungsdatum: 21.06.2006
Beiträge: 17
Beitrag pmneo Mitglied 09:08:12 20.11.2006   Titel:              Zitieren

Kleines Update!!

Damit der Speicher nicht volläuft sollte der Teil in Step 7 so aussehen:

C/C++ Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// 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++;
    }

    }
C/C++ Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// 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++;
}

}
C/C++ Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// 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++;
    }

    }
estartu
Moderator

Benutzerprofil
Anmeldungsdatum: 05.09.2003
Beiträge: 11494
Beitrag estartu Moderator 09:09:55 20.11.2006   Titel:              Zitieren

Jochen Kalmbach schrieb:
Aber eher was für die WinAPI-FAQ ;)
Na, dann schieb ich es da mal hin. :)
Falls es dort nicht erwünscht ist, bitte in die MFC FAQ schieben. ;)

_________________
Das c-plusplus.de-Magazin sucht Mitmacher --- Die Artikel --- meine Homepage
C/C++ Forum :: FAQ - WinAPI ::  CPU Auslastung bei DualCore CPU's einzeln Auslesen?   Auf Beitrag antworten

Zeige alle Beiträge auf einer Seite




Nächstes Thema anzeigen
Vorheriges Thema anzeigen
Sie können keine Beiträge in dieses Forum schreiben.
Sie können auf Beiträge in diesem Forum nicht antworten.
Sie können Ihre Beiträge in diesem Forum nicht bearbeiten.
Sie können Ihre Beiträge in diesem Forum nicht löschen.
Sie können an Umfragen in diesem Forum nicht mitmachen.

Powered by phpBB © 2001, 2002 phpBB Group :: FI Theme

c++.de ist Teilnehmer des Partnerprogramms von Amazon Europe S.à.r.l. und Partner des Werbeprogramms, das zur Bereitstellung eines Mediums für Websites konzipiert wurde, mittels dessen durch die Platzierung von Werbeanzeigen und Links zu amazon.de Werbekostenerstattung verdient werden kann.

Die Vervielfältigung der auf den Seiten www.c-plusplus.de, www.c-plusplus.info, www.c-sar.de, www.c-plusplus.net und www.baeckmann.de enthaltenen Informationen ohne eine schriftliche Genehmigung des Seitenbetreibers ist untersagt (vgl. §4 Urheberrechtsgesetz). Die Nutzung und Änderung der vorgestellten Strukturen und Verfahren in privaten und kommerziellen Softwareanwendungen ist ausdrücklich erlaubt, soweit keine Rechte Dritter verletzt werden. Der Seitenbetreiber übernimmt keine Gewähr für die Funktion einzelner Beiträge oder Programmfragmente, insbesondere übernimmt er keine Haftung für eventuelle aus dem Gebrauch entstehenden Folgeschäden.