Programmatically retrieve peak virtual memory of a process

I'm trying to find out the peak virtual memory of my running process on Linux, macOS and FreeBSD.

I'm focusing on peak virtual memory as this is a relevant measure of the peak memory usage of my process at any given point, beyond the limits of physical RAM (what peak RSS would provide).

In the spirit of How to determine CPU and memory consumption from inside a process? I'm planning to use this post to compile solutions for these three platforms (I'll be happy to extend it to more platforms if you have working code to provide).

Windows

On Windows, the following appears to return the same values as Process Explorer:

PROCESS_MEMORY_COUNTERS_EX pmc;
GetProcessMemoryInfo(
    GetCurrentProcess(),
    reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&pmc),
    sizeof(pmc));
return pmc.PeakPagefileUsage;

Linux

Is parsing the output of /proc/self/status the best/only option on Linux? Do all Linux flavors return the same information formatted in the exact same way?

For reference, here's a sample output on Ubuntu:

root@appleseedhq:~# cat /proc/self/status
Name:   cat
State:  R (running)
Tgid:   12975
Ngid:   0
Pid:    12975
PPid:   12938
TracerPid:      0
Uid:    0       0       0       0
Gid:    0       0       0       0
FDSize: 256
Groups: 0
VmPeak:     7220 kB
VmSize:     7220 kB
VmLck:         0 kB
VmPin:         0 kB
VmHWM:       608 kB
VmRSS:       608 kB
VmData:      176 kB
VmStk:       136 kB
VmExe:        44 kB
VmLib:      1924 kB
VmPTE:        40 kB
VmSwap:        0 kB
Threads:        1
(more stuff...)

The line of interest here appears to be

VmPeak:     7220 kB

Any simpler, faster and less brittle solution?

macOS

On macOS I thought that using task_info() with TASK_BASIC_INFO or MACH_TASK_BASIC_INFO would do the job, ie

#ifdef MACH_TASK_BASIC_INFO
    struct mach_task_basic_info info;
    mach_msg_type_number_t info_count = MACH_TASK_BASIC_INFO_COUNT;

    if (task_info(
            mach_task_self(),
            MACH_TASK_BASIC_INFO,
            (task_info_t)&info,
            &info_count) != KERN_SUCCESS)
        return 0;
#else
    struct task_basic_info info;
    mach_msg_type_number_t info_count = TASK_BASIC_INFO_COUNT;

    if (task_info(
            mach_task_self(),
            TASK_BASIC_INFO,
            (task_info_t)&info,
            &info_count) != KERN_SUCCESS)
        return 0;
#endif

Unfortunately, while close, it doesn't look like I can get peak virtual memory of a process, only current virtual memory usage (in info.virtual_size , in bytes).

FreeBSD

Again, on FreeBSD I thought that getrusage() would provide the info but it doesn't appear to have anything about peak virtual memory.

链接地址: http://www.djcxy.com/p/79828.html

上一篇: 堆栈内存是否有限制?

下一篇: 以编程方式检索进程的峰值虚拟内存