psapi.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # Windows PSAPI function wrappers.
  2. # http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/psapi_functions.asp
  3. #
  4. # The contents of this file are subject to the Python Software Foundation
  5. # License Version 2.3 (the License). You may not copy or use this file, in
  6. # either source code or executable form, except in compliance with the License.
  7. # You may obtain a copy of the License at http://www.python.org/license.
  8. #
  9. # Software distributed under the License is distributed on an AS IS basis,
  10. # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11. # for the specific language governing rights and limitations under the
  12. # License.
  13. #
  14. # by Greg Hazel
  15. import ctypes
  16. DWORD = ctypes.c_ulong
  17. SIZE_T = ctypes.c_ulong
  18. psapi = ctypes.windll.psapi
  19. Kernel32 = ctypes.windll.Kernel32
  20. class PROCESS_MEMORY_COUNTERS(ctypes.Structure):
  21. _fields_ = [("cb", DWORD),
  22. ("PageFaultCount", DWORD),
  23. ("PeakWorkingSetSize", SIZE_T),
  24. ("WorkingSetSize", SIZE_T),
  25. ("QuotaPeakPagedPoolUsage", SIZE_T),
  26. ("QuotaPagedPoolUsage", SIZE_T),
  27. ("QuotaPeakNonPagedPoolUsage", SIZE_T),
  28. ("QuotaNonPagedPoolUsage", SIZE_T),
  29. ("PagefileUsage", SIZE_T),
  30. ("PeakPagefileUsage", SIZE_T),
  31. ]
  32. class PROCESS_MEMORY_COUNTERS_EX(ctypes.Structure):
  33. _fields_ = [("cb", DWORD),
  34. ("PageFaultCount", DWORD),
  35. ("PeakWorkingSetSize", SIZE_T),
  36. ("WorkingSetSize", SIZE_T),
  37. ("QuotaPeakPagedPoolUsage", SIZE_T),
  38. ("QuotaPagedPoolUsage", SIZE_T),
  39. ("QuotaPeakNonPagedPoolUsage", SIZE_T),
  40. ("QuotaNonPagedPoolUsage", SIZE_T),
  41. ("PagefileUsage", SIZE_T),
  42. ("PeakPagefileUsage", SIZE_T),
  43. ("PrivateUsage", SIZE_T),
  44. ]
  45. def GetCurrentProcess():
  46. return Kernel32.GetCurrentProcess()
  47. def GetProcessMemoryInfo(handle):
  48. psmemCounters = PROCESS_MEMORY_COUNTERS_EX()
  49. cb = DWORD(ctypes.sizeof(psmemCounters))
  50. b = psapi.GetProcessMemoryInfo(handle, ctypes.byref(psmemCounters), cb)
  51. if not b:
  52. psmemCounters = PROCESS_MEMORY_COUNTERS()
  53. cb = DWORD(ctypes.sizeof(psmemCounters))
  54. b = psapi.GetProcessMemoryInfo(handle, ctypes.byref(psmemCounters), cb)
  55. if not b:
  56. raise ctypes.WinError()
  57. d = {}
  58. for k, t in psmemCounters._fields_:
  59. d[k] = getattr(psmemCounters, k)
  60. return d