"Private Bytes"没有反映它。如何找到进程分配的确切内存?

"Private Bytes" doesn't reflect it. How to find exact memory allocated by process?

本文关键字:分配 进程 内存 何找 Bytes Private      更新时间:2023-10-16

下面是使用VS2010在Windows XP上编译和运行的c++代码示例。

在分配前后打印"private bytes"

void PrintPrivateBytes()
{
    HANDLE current_process;
    PROCESS_MEMORY_COUNTERS_EX pmc;
    current_process = GetCurrentProcess();
    if (!GetProcessMemoryInfo(current_process, (PPROCESS_MEMORY_COUNTERS)&pmc, sizeof(pmc)))
    {
        std::cout << "nGetProcessMemoryInfo failed" ;
        return;
    }
    std::cout << "nProcess private bytes: " << pmc.PrivateUsage/1024 << " KB"; 
}
int _tmain(int argc, _TCHAR* argv[])
{
    // Code demonstrating private bytes doesn't change
    std::cout << "nnBefore allocating memory" ;
    PrintPrivateBytes();
    char* charptr = new char[8192];
    std::cout << "nnAfter allocating 8 KB memory" ;
    PrintPrivateBytes();
    delete[] charptr;
    std::cout << "nnAfter deleting memory" ;
    PrintPrivateBytes();
    int RetVal = _heapmin();
    std::cout << "nnAfter calling _heapmin" ;
    PrintPrivateBytes();
    return 0;
}

输出:

分配内存前

进程私有字节:416 KB

分配内存后

进程私有字节:428 KB

删除内存后

进程私有字节:428 KB

调用_heapmin后

进程私有字节:428 KB

表示"私有字节"不能准确反映进程的内存使用情况。

哪个Windows API/结构将有助于找到确切的进程的内存使用情况?(工作组也没用。它只是反映了物理内存的使用情况)

您检查私有字节的解决方案是正确的,只有您对_heapmin的假设是错误的。

_heapmin不能正常工作。_heapmin在文档中描述为"向操作系统释放未使用的堆内存"。

实现(见"Program Files (x86)Microsoft Visual Studio 10.0VCcrtsrcheapmin.c")是

int __cdecl _heapmin(void)
{
        if ( HeapCompact( _crtheap, 0 ) == 0 ) {
            return -1;
        }
        else {
            return 0;
        }
}
在文档中,尽管返回堆中最大空闲块的大小,但HeapCompact通常什么也不做。如果使用了一个特殊的全局(调试目的)标志,它只会做一些额外的事情。