Debian Codegraph @

psutil/arch/windows/mem.c

raw
1 /*
2 * Copyright (c) 2009, Jay Loden, 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 <Psapi.h>
10 #include <pdh.h>
11
12 #include "../../arch/all/init.h"
13
14
15 PyObject *
16 psutil_getpagesize(PyObject *self, PyObject *args) {
17 // XXX: we may want to use GetNativeSystemInfo to differentiate
18 // page size for WoW64 processes (but am not sure).
19 return Py_BuildValue("I", PSUTIL_SYSTEM_INFO.dwPageSize);
20 }
21
22
23 PyObject *
24 psutil_virtual_mem(PyObject *self, PyObject *args) {
25 unsigned long long totalPhys, availPhys, totalSys, availSys, pageSize;
26 PERFORMANCE_INFORMATION perfInfo;
27
28 if (! GetPerformanceInfo(&perfInfo, sizeof(PERFORMANCE_INFORMATION))) {
29 PyErr_SetFromWindowsErr(0);
30 return NULL;
31 }
32 // values are size_t, widen (if needed) to long long
33 pageSize = perfInfo.PageSize;
34 totalPhys = perfInfo.PhysicalTotal * pageSize;
35 availPhys = perfInfo.PhysicalAvailable * pageSize;
36 totalSys = perfInfo.CommitLimit * pageSize;
37 availSys = totalSys - perfInfo.CommitTotal * pageSize;
38 return Py_BuildValue(
39 "(LLLL)",
40 totalPhys,
41 availPhys,
42 totalSys,
43 availSys);
44 }
45
46
47 // Return a float representing the percent usage of all paging files on
48 // the system.
49 PyObject *
50 psutil_swap_percent(PyObject *self, PyObject *args) {
51 WCHAR *szCounterPath = L"\\Paging File(_Total)\\% Usage";
52 PDH_STATUS s;
53 HQUERY hQuery;
54 HCOUNTER hCounter;
55 PDH_FMT_COUNTERVALUE counterValue;
56 double percentUsage;
57
58 if ((PdhOpenQueryW(NULL, 0, &hQuery)) != ERROR_SUCCESS) {
59 PyErr_Format(PyExc_RuntimeError, "PdhOpenQueryW failed");
60 return NULL;
61 }
62
63 s = PdhAddEnglishCounterW(hQuery, szCounterPath, 0, &hCounter);
64 if (s != ERROR_SUCCESS) {
65 PdhCloseQuery(hQuery);
66 PyErr_Format(
67 PyExc_RuntimeError,
68 "PdhAddEnglishCounterW failed. Performance counters may be disabled."
69 );
70 return NULL;
71 }
72
73 s = PdhCollectQueryData(hQuery);
74 if (s != ERROR_SUCCESS) {
75 // If swap disabled this will fail.
76 psutil_debug("PdhCollectQueryData failed; assume swap percent is 0");
77 percentUsage = 0;
78 }
79 else {
80 s = PdhGetFormattedCounterValue(
81 (PDH_HCOUNTER)hCounter, PDH_FMT_DOUBLE, 0, &counterValue);
82 if (s != ERROR_SUCCESS) {
83 PdhCloseQuery(hQuery);
84 PyErr_Format(
85 PyExc_RuntimeError, "PdhGetFormattedCounterValue failed");
86 return NULL;
87 }
88 percentUsage = counterValue.doubleValue;
89 }
90
91 PdhRemoveCounter(hCounter);
92 PdhCloseQuery(hQuery);
93 return Py_BuildValue("d", percentUsage);
94 }