所以我正在尝试通过 python 获取我的 PC 的可用内存和总内存。这就是我现在所拥有的:
def get_memory_status():
kernel32 = ctypes.windll.kernel32
c_ulong = ctypes.c_ulong
class MEMORYSTATUS(ctypes.Structure):
_fields_ = [
("dwLength", c_ulong),
("dwMemoryLoad", c_ulong),
("dwTotalPhys", c_ulong),
("dwAvailPhys", c_ulong),
("dwTotalPageFile", c_ulong),
("dwAvailPageFile", c_ulong),
("dwTotalVirtual", c_ulong),
("dwAvailVirtual", c_ulong)
]
memoryStatus = MEMORYSTATUS()
memoryStatus.dwLength = ctypes.sizeof(MEMORYSTATUS)
kernel32.GlobalMemoryStatus(ctypes.byref(memoryStatus))
return (memoryStatus.dwAvailPhys, memoryStatus.dwTotalPhys)
avail, total = get_memory_status()
print avail + " " + total
如果我执行此操作,我总是会得到相同的可用 RAM 值和总 RAM 值。当我请求 dwMemoryLoad
时,我得到的值与 Window 的任务管理器中显示的“物理内存”相同,它是已用 RAM 的百分比(不是 0)。但我想要精确的字节数。难道我做错了什么?
我不能使用任何额外的库,如果可以的话,我早就用过了。
最佳答案
根据 GlobalMemoryStatus MSDN entry 的说明:
On Intel x86 computers with more than 2 GB and less than 4 GB of memory, the GlobalMemoryStatus function will always return 2 GB in the dwTotalPhys member of the MEMORYSTATUS structure. Similarly, if the total available memory is between 2 and 4 GB, the dwAvailPhys member of the MEMORYSTATUS structure will be rounded down to 2 GB. If the executable is linked using the /LARGEADDRESSAWARE linker option, then the GlobalMemoryStatus function will return the correct amount of physical memory in both members.
而且,在文章的顶部,有:
[GlobalMemoryStatus can return incorrect information. Use the GlobalMemoryStatusEx function instead.]
顺便说一句,这个函数存在于 pywin32
库中。
关于python - 可用内存和总内存始终相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27228166/