diff options
author | Daniel Widdis <widdis@gmail.com> | 2023-04-13 01:11:27 -0700 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-04-13 10:11:27 +0200 |
commit | 0dde184075f81a9b6e22caa7255396d21ae63769 (patch) | |
tree | d234e2a26bc6b77c576a0ddea6de42f61a96c4da /psutil/arch | |
parent | 67d988aeb5701bca3cc84795ae3f249b5c843451 (diff) | |
download | psutil-0dde184075f81a9b6e22caa7255396d21ae63769.tar.gz |
Get Windows percent swap usage from performance counters (#2160)
Signed-off-by: Daniel Widdis <widdis@gmail.com>
Diffstat (limited to 'psutil/arch')
-rw-r--r-- | psutil/arch/windows/mem.c | 51 | ||||
-rw-r--r-- | psutil/arch/windows/mem.h | 1 |
2 files changed, 52 insertions, 0 deletions
diff --git a/psutil/arch/windows/mem.c b/psutil/arch/windows/mem.c index 18b535e6..24dc15ad 100644 --- a/psutil/arch/windows/mem.c +++ b/psutil/arch/windows/mem.c @@ -7,6 +7,7 @@ #include <Python.h> #include <windows.h> #include <Psapi.h> +#include <pdh.h> #include "../../_psutil_common.h" @@ -41,3 +42,53 @@ psutil_virtual_mem(PyObject *self, PyObject *args) { totalSys, availSys); } + + +// Return a float representing the percent usage of all paging files on +// the system. +PyObject * +psutil_swap_percent(PyObject *self, PyObject *args) { + WCHAR *szCounterPath = L"\\Paging File(_Total)\\% Usage"; + PDH_STATUS s; + HQUERY hQuery; + HCOUNTER hCounter; + PDH_FMT_COUNTERVALUE counterValue; + double percentUsage; + + if ((PdhOpenQueryW(NULL, 0, &hQuery)) != ERROR_SUCCESS) { + PyErr_Format(PyExc_RuntimeError, "PdhOpenQueryW failed"); + return NULL; + } + + s = PdhAddEnglishCounterW(hQuery, szCounterPath, 0, &hCounter); + if (s != ERROR_SUCCESS) { + PdhCloseQuery(hQuery); + PyErr_Format( + PyExc_RuntimeError, + "PdhAddEnglishCounterW failed. Performance counters may be disabled." + ); + return NULL; + } + + s = PdhCollectQueryData(hQuery); + if (s != ERROR_SUCCESS) { + // If swap disabled this will fail. + psutil_debug("PdhCollectQueryData failed; assume swap percent is 0"); + percentUsage = 0; + } + else { + s = PdhGetFormattedCounterValue( + (PDH_HCOUNTER)hCounter, PDH_FMT_DOUBLE, 0, &counterValue); + if (s != ERROR_SUCCESS) { + PdhCloseQuery(hQuery); + PyErr_Format( + PyExc_RuntimeError, "PdhGetFormattedCounterValue failed"); + return NULL; + } + percentUsage = counterValue.doubleValue; + } + + PdhRemoveCounter(hCounter); + PdhCloseQuery(hQuery); + return Py_BuildValue("d", percentUsage); +} diff --git a/psutil/arch/windows/mem.h b/psutil/arch/windows/mem.h index a10781df..48d3dade 100644 --- a/psutil/arch/windows/mem.h +++ b/psutil/arch/windows/mem.h @@ -8,3 +8,4 @@ PyObject *psutil_getpagesize(PyObject *self, PyObject *args); PyObject *psutil_virtual_mem(PyObject *self, PyObject *args); +PyObject *psutil_swap_percent(PyObject *self, PyObject *args); |