Debian Codegraph @

psutil/arch/windows/cpu.c

raw
1 /*
2 * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
3 * Use of this source code is governed by a BSD-style license that can be
4 * found in the LICENSE file.
5 */
6
7 #include <Python.h>
8 #include <windows.h>
9 #include <PowrProf.h>
10
11 #include "../../arch/all/init.h"
12
13
14 /*
15 * Return the number of logical, active CPUs. Return 0 if undetermined.
16 * See discussion at: https://bugs.python.org/issue33166#msg314631
17 */
18 static unsigned int
19 psutil_get_num_cpus(int fail_on_err) {
20 unsigned int ncpus = 0;
21
22 // Minimum requirement: Windows 7
23 if (GetActiveProcessorCount != NULL) {
24 ncpus = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
25 if ((ncpus == 0) && (fail_on_err == 1)) {
26 PyErr_SetFromWindowsErr(0);
27 }
28 }
29 else {
30 psutil_debug("GetActiveProcessorCount() not available; "
31 "using GetSystemInfo()");
32 ncpus = (unsigned int)PSUTIL_SYSTEM_INFO.dwNumberOfProcessors;
33 if ((ncpus <= 0) && (fail_on_err == 1)) {
34 PyErr_SetString(
35 PyExc_RuntimeError,
36 "GetSystemInfo() failed to retrieve CPU count");
37 }
38 }
39 return ncpus;
40 }
41
42
43 /*
44 * Retrieves system CPU timing information as a (user, system, idle)
45 * tuple. On a multiprocessor system, the values returned are the
46 * sum of the designated times across all processors.
47 */
48 PyObject *
49 psutil_cpu_times(PyObject *self, PyObject *args) {
50 double idle, kernel, user, system;
51 FILETIME idle_time, kernel_time, user_time;
52
53 if (!GetSystemTimes(&idle_time, &kernel_time, &user_time)) {
54 PyErr_SetFromWindowsErr(0);
55 return NULL;
56 }
57
58 idle = (double)((HI_T * idle_time.dwHighDateTime) + \
59 (LO_T * idle_time.dwLowDateTime));
60 user = (double)((HI_T * user_time.dwHighDateTime) + \
61 (LO_T * user_time.dwLowDateTime));
62 kernel = (double)((HI_T * kernel_time.dwHighDateTime) + \
63 (LO_T * kernel_time.dwLowDateTime));
64
65 // Kernel time includes idle time.
66 // We return only busy kernel time subtracting idle time from
67 // kernel time.
68 system = (kernel - idle);
69 return Py_BuildValue("(ddd)", user, system, idle);
70 }
71
72
73 /*
74 * Same as above but for all system CPUs.
75 */
76 PyObject *
77 psutil_per_cpu_times(PyObject *self, PyObject *args) {
78 double idle, kernel, systemt, user, interrupt, dpc;
79 NTSTATUS status;
80 _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION *sppi = NULL;
81 UINT i;
82 unsigned int ncpus;
83 PyObject *py_tuple = NULL;
84 PyObject *py_retlist = PyList_New(0);
85
86 if (py_retlist == NULL)
87 return NULL;
88
89 // retrieves number of processors
90 ncpus = psutil_get_num_cpus(1);
91 if (ncpus == 0)
92 goto error;
93
94 // allocates an array of _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION
95 // structures, one per processor
96 sppi = (_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION *) \
97 malloc(ncpus * sizeof(_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION));
98 if (sppi == NULL) {
99 PyErr_NoMemory();
100 goto error;
101 }
102
103 // gets cpu time information
104 status = NtQuerySystemInformation(
105 SystemProcessorPerformanceInformation,
106 sppi,
107 ncpus * sizeof(_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION),
108 NULL);
109 if (! NT_SUCCESS(status)) {
110 psutil_SetFromNTStatusErr(
111 status,
112 "NtQuerySystemInformation(SystemProcessorPerformanceInformation)"
113 );
114 goto error;
115 }
116
117 // computes system global times summing each
118 // processor value
119 idle = user = kernel = interrupt = dpc = 0;
120 for (i = 0; i < ncpus; i++) {
121 py_tuple = NULL;
122 user = (double)((HI_T * sppi[i].UserTime.HighPart) +
123 (LO_T * sppi[i].UserTime.LowPart));
124 idle = (double)((HI_T * sppi[i].IdleTime.HighPart) +
125 (LO_T * sppi[i].IdleTime.LowPart));
126 kernel = (double)((HI_T * sppi[i].KernelTime.HighPart) +
127 (LO_T * sppi[i].KernelTime.LowPart));
128 interrupt = (double)((HI_T * sppi[i].InterruptTime.HighPart) +
129 (LO_T * sppi[i].InterruptTime.LowPart));
130 dpc = (double)((HI_T * sppi[i].DpcTime.HighPart) +
131 (LO_T * sppi[i].DpcTime.LowPart));
132
133 // kernel time includes idle time on windows
134 // we return only busy kernel time subtracting
135 // idle time from kernel time
136 systemt = kernel - idle;
137 py_tuple = Py_BuildValue(
138 "(ddddd)",
139 user,
140 systemt,
141 idle,
142 interrupt,
143 dpc
144 );
145 if (!py_tuple)
146 goto error;
147 if (PyList_Append(py_retlist, py_tuple))
148 goto error;
149 Py_CLEAR(py_tuple);
150 }
151
152 free(sppi);
153 return py_retlist;
154
155 error:
156 Py_XDECREF(py_tuple);
157 Py_DECREF(py_retlist);
158 if (sppi)
159 free(sppi);
160 return NULL;
161 }
162
163
164 /*
165 * Return the number of active, logical CPUs.
166 */
167 PyObject *
168 psutil_cpu_count_logical(PyObject *self, PyObject *args) {
169 unsigned int ncpus;
170
171 ncpus = psutil_get_num_cpus(0);
172 if (ncpus != 0)
173 return Py_BuildValue("I", ncpus);
174 else
175 Py_RETURN_NONE; // mimic os.cpu_count()
176 }
177
178
179 /*
180 * Return the number of CPU cores (non hyper-threading).
181 */
182 PyObject *
183 psutil_cpu_count_cores(PyObject *self, PyObject *args) {
184 DWORD rc;
185 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX buffer = NULL;
186 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX ptr = NULL;
187 DWORD length = 0;
188 DWORD offset = 0;
189 DWORD ncpus = 0;
190 DWORD prev_processor_info_size = 0;
191
192 // GetLogicalProcessorInformationEx() is available from Windows 7
193 // onward. Differently from GetLogicalProcessorInformation()
194 // it supports process groups, meaning this is able to report more
195 // than 64 CPUs. See:
196 // https://bugs.python.org/issue33166
197 if (GetLogicalProcessorInformationEx == NULL) {
198 psutil_debug("Win < 7; cpu_count_cores() forced to None");
199 Py_RETURN_NONE;
200 }
201
202 while (1) {
203 rc = GetLogicalProcessorInformationEx(
204 RelationAll, buffer, &length);
205 if (rc == FALSE) {
206 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
207 if (buffer) {
208 free(buffer);
209 }
210 buffer = \
211 (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX)malloc(length);
212 if (NULL == buffer) {
213 PyErr_NoMemory();
214 return NULL;
215 }
216 }
217 else {
218 psutil_debug("GetLogicalProcessorInformationEx() returned %u",
219 GetLastError());
220 goto return_none;
221 }
222 }
223 else {
224 break;
225 }
226 }
227
228 ptr = buffer;
229 while (offset < length) {
230 // Advance ptr by the size of the previous
231 // SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX struct.
232 ptr = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) \
233 (((char*)ptr) + prev_processor_info_size);
234
235 if (ptr->Relationship == RelationProcessorCore) {
236 ncpus += 1;
237 }
238
239 // When offset == length, we've reached the last processor
240 // info struct in the buffer.
241 offset += ptr->Size;
242 prev_processor_info_size = ptr->Size;
243 }
244
245 free(buffer);
246 if (ncpus != 0) {
247 return Py_BuildValue("I", ncpus);
248 }
249 else {
250 psutil_debug("GetLogicalProcessorInformationEx() count was 0");
251 Py_RETURN_NONE; // mimic os.cpu_count()
252 }
253
254 return_none:
255 if (buffer != NULL)
256 free(buffer);
257 Py_RETURN_NONE;
258 }
259
260
261 /*
262 * Return CPU statistics.
263 */
264 PyObject *
265 psutil_cpu_stats(PyObject *self, PyObject *args) {
266 NTSTATUS status;
267 _SYSTEM_PERFORMANCE_INFORMATION *spi = NULL;
268 _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION *sppi = NULL;
269 _SYSTEM_INTERRUPT_INFORMATION *InterruptInformation = NULL;
270 unsigned int ncpus;
271 UINT i;
272 ULONG64 dpcs = 0;
273 ULONG interrupts = 0;
274
275 // retrieves number of processors
276 ncpus = psutil_get_num_cpus(1);
277 if (ncpus == 0)
278 goto error;
279
280 // get syscalls / ctx switches
281 spi = (_SYSTEM_PERFORMANCE_INFORMATION *) \
282 malloc(ncpus * sizeof(_SYSTEM_PERFORMANCE_INFORMATION));
283 if (spi == NULL) {
284 PyErr_NoMemory();
285 goto error;
286 }
287 status = NtQuerySystemInformation(
288 SystemPerformanceInformation,
289 spi,
290 ncpus * sizeof(_SYSTEM_PERFORMANCE_INFORMATION),
291 NULL);
292 if (! NT_SUCCESS(status)) {
293 psutil_SetFromNTStatusErr(
294 status, "NtQuerySystemInformation(SystemPerformanceInformation)");
295 goto error;
296 }
297
298 // get DPCs
299 InterruptInformation = \
300 malloc(sizeof(_SYSTEM_INTERRUPT_INFORMATION) * ncpus);
301 if (InterruptInformation == NULL) {
302 PyErr_NoMemory();
303 goto error;
304 }
305
306 status = NtQuerySystemInformation(
307 SystemInterruptInformation,
308 InterruptInformation,
309 ncpus * sizeof(SYSTEM_INTERRUPT_INFORMATION),
310 NULL);
311 if (! NT_SUCCESS(status)) {
312 psutil_SetFromNTStatusErr(
313 status, "NtQuerySystemInformation(SystemInterruptInformation)");
314 goto error;
315 }
316 for (i = 0; i < ncpus; i++) {
317 dpcs += InterruptInformation[i].DpcCount;
318 }
319
320 // get interrupts
321 sppi = (_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION *) \
322 malloc(ncpus * sizeof(_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION));
323 if (sppi == NULL) {
324 PyErr_NoMemory();
325 goto error;
326 }
327
328 status = NtQuerySystemInformation(
329 SystemProcessorPerformanceInformation,
330 sppi,
331 ncpus * sizeof(_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION),
332 NULL);
333 if (! NT_SUCCESS(status)) {
334 psutil_SetFromNTStatusErr(
335 status,
336 "NtQuerySystemInformation(SystemProcessorPerformanceInformation)");
337 goto error;
338 }
339
340 for (i = 0; i < ncpus; i++) {
341 interrupts += sppi[i].InterruptCount;
342 }
343
344 // done
345 free(spi);
346 free(InterruptInformation);
347 free(sppi);
348 return Py_BuildValue(
349 "kkkk",
350 spi->ContextSwitches,
351 interrupts,
352 (unsigned long)dpcs,
353 spi->SystemCalls
354 );
355
356 error:
357 if (spi)
358 free(spi);
359 if (InterruptInformation)
360 free(InterruptInformation);
361 if (sppi)
362 free(sppi);
363 return NULL;
364 }
365
366
367 /*
368 * Return CPU frequency.
369 */
370 PyObject *
371 psutil_cpu_freq(PyObject *self, PyObject *args) {
372 PROCESSOR_POWER_INFORMATION *ppi;
373 NTSTATUS ret;
374 ULONG size;
375 LPBYTE pBuffer = NULL;
376 ULONG current;
377 ULONG max;
378 unsigned int ncpus;
379
380 // Get the number of CPUs.
381 ncpus = psutil_get_num_cpus(1);
382 if (ncpus == 0)
383 return NULL;
384
385 // Allocate size.
386 size = ncpus * sizeof(PROCESSOR_POWER_INFORMATION);
387 pBuffer = (BYTE*)LocalAlloc(LPTR, size);
388 if (! pBuffer) {
389 PyErr_SetFromWindowsErr(0);
390 return NULL;
391 }
392
393 // Syscall.
394 ret = CallNtPowerInformation(
395 ProcessorInformation, NULL, 0, pBuffer, size);
396 if (ret != 0) {
397 PyErr_SetString(PyExc_RuntimeError,
398 "CallNtPowerInformation syscall failed");
399 goto error;
400 }
401
402 // Results.
403 ppi = (PROCESSOR_POWER_INFORMATION *)pBuffer;
404 max = ppi->MaxMhz;
405 current = ppi->CurrentMhz;
406 LocalFree(pBuffer);
407
408 return Py_BuildValue("kk", current, max);
409
410 error:
411 if (pBuffer != NULL)
412 LocalFree(pBuffer);
413 return NULL;
414 }