简体   繁体   中英

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

Here is sample piece of C++ code compiled and run using VS2010 on Windows XP.

It prints "private bytes" before and after allocation.

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 << "\n\nBefore allocating memory" ;
    PrintPrivateBytes();

    char* charptr = new char[8192];
    std::cout << "\n\nAfter allocating 8 KB memory" ;
    PrintPrivateBytes();

    delete[] charptr;
    std::cout << "\n\nAfter deleting memory" ;
    PrintPrivateBytes();

    int RetVal = _heapmin();
    std::cout << "\n\nAfter calling _heapmin" ;
    PrintPrivateBytes();

    return 0;
}

Here is output:

Before allocating memory

Process private bytes: 416 KB

After allocating memory

Process private bytes: 428 KB

After deleting memory

Process private bytes: 428 KB

After calling _heapmin

Process private bytes: 428 KB

It indicates "private bytes" doesn't reflect exact memory usage of process.

Which Windows API/structure will help finding exact memory usage of process ? (Working set is also of no use. It just reflect much how physical memory is being used)

Your solution of checking the private bytes is correct, only your assumption about _heapmin is wrong.

_heapmin does not work as documented. _heapmin is documented as "Releases unused heap memory to the operating system."

The implementation (see "\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\crt\\src\\heapmin.c") is

int __cdecl _heapmin(void)
{
        if ( HeapCompact( _crtheap, 0 ) == 0 ) {
            return -1;
        }
        else {
            return 0;
        }
}

HeapCompact is documented to normally do quite nothing despite returning the size of the largest free block in the heap. It only does some extra stuff if a special global (debug purpose) flag is used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM