osinfo.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
  2. # For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt
  3. """OS information for testing."""
  4. from coverage import env
  5. if env.WINDOWS:
  6. # Windows implementation
  7. def process_ram():
  8. """How much RAM is this process using? (Windows)"""
  9. import ctypes
  10. # From: http://lists.ubuntu.com/archives/bazaar-commits/2009-February/011990.html
  11. class PROCESS_MEMORY_COUNTERS_EX(ctypes.Structure):
  12. """Used by GetProcessMemoryInfo"""
  13. _fields_ = [
  14. ('cb', ctypes.c_ulong),
  15. ('PageFaultCount', ctypes.c_ulong),
  16. ('PeakWorkingSetSize', ctypes.c_size_t),
  17. ('WorkingSetSize', ctypes.c_size_t),
  18. ('QuotaPeakPagedPoolUsage', ctypes.c_size_t),
  19. ('QuotaPagedPoolUsage', ctypes.c_size_t),
  20. ('QuotaPeakNonPagedPoolUsage', ctypes.c_size_t),
  21. ('QuotaNonPagedPoolUsage', ctypes.c_size_t),
  22. ('PagefileUsage', ctypes.c_size_t),
  23. ('PeakPagefileUsage', ctypes.c_size_t),
  24. ('PrivateUsage', ctypes.c_size_t),
  25. ]
  26. mem_struct = PROCESS_MEMORY_COUNTERS_EX()
  27. ret = ctypes.windll.psapi.GetProcessMemoryInfo(
  28. ctypes.windll.kernel32.GetCurrentProcess(),
  29. ctypes.byref(mem_struct),
  30. ctypes.sizeof(mem_struct)
  31. )
  32. if not ret:
  33. return 0
  34. return mem_struct.PrivateUsage
  35. elif env.LINUX:
  36. # Linux implementation
  37. import os
  38. _scale = {'kb': 1024, 'mb': 1024*1024}
  39. def _VmB(key):
  40. """Read the /proc/PID/status file to find memory use."""
  41. try:
  42. # Get pseudo file /proc/<pid>/status
  43. with open('/proc/%d/status' % os.getpid()) as t:
  44. v = t.read()
  45. except IOError:
  46. return 0 # non-Linux?
  47. # Get VmKey line e.g. 'VmRSS: 9999 kB\n ...'
  48. i = v.index(key)
  49. v = v[i:].split(None, 3)
  50. if len(v) < 3:
  51. return 0 # Invalid format?
  52. # Convert Vm value to bytes.
  53. return int(float(v[1]) * _scale[v[2].lower()])
  54. def process_ram():
  55. """How much RAM is this process using? (Linux implementation)"""
  56. return _VmB('VmRSS')
  57. else:
  58. # Generic implementation.
  59. def process_ram():
  60. """How much RAM is this process using? (stdlib implementation)"""
  61. import resource
  62. return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss