python - 可用内存和总内存始终相同

标签 python windows memory ctypes ram

所以我正在尝试通过 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/

相关文章:

windows - “git”不被识别为内部或外部命令

java - 垃圾收集器如何快速知道哪些对象不再有对它们的引用?

c++ - 优化图像缓冲区

python - 为什么子进程在 Windows 上启动时导入主模块,而在 Linux 上则不然?

Python JSON 排序嵌套数据

windows - Windows 上 Bugzilla 的电子邮件服务器

windows - ANSI 转义序列不会打印到 Windows 上的标准输出

c# - 为什么 .net 程序在计算机有更多 ram 时使用更多 VirtualMemorySize64

python - Elasticsearch-dsl 排序,查找最后 X 个条目

python - 是否可以将代码从文本编辑器发送到现有的 ipython 控制台