获取一段时间间隔的内存高水位线

Zac*_*chB 5 linux memory memory-management

我正在尝试获取长时间运行的 Linux 进程在短时间内使用的最大内存量。例如,类似:

resetmaxrss(); // hypothetical new command
void* foo = malloc(4096);
free(foo);
getrusage(...); // 'ru_maxrss' reports 4096 plus whatever else is alive

resetmaxrss();
void* bar = malloc(2048);
free(bar);
getrusage(...); // 'ru_maxrss' reports 2048 + whatever, *not* 4096
Run Code Online (Sandbox Code Playgroud)

我发现并排除的选项:

  • getrusage的最大 RSS 无法重置。
  • cgmemtimewait4似乎在幕后使用,因此在进程运行时查询进程是不可行的。
  • tstime报告退出进程,因此在进程运行时查询进程也是不可行的。

其他选项,但都不好:

  • 轮询。很容易错过我们的简短分配。
  • 检测我们的代码。我们无法访问所有正在使用的内存分配器,因此这不会非常优雅或简单。为了准确性,我还宁愿使用操作系统报告的值。

除了提出 Linux 内核补丁之外,有没有办法做到这一点?

Zac*_*chB 6

事实证明,从Linux 4.0开始,RSS峰值可以重置:

/proc/[pid]/clear_refs (since Linux 2.6.22)

    This is a write-only file, writable only by owner of the
    process.

    The following values may be written to the file:

    [snip]

    5 (since Linux 4.0)
        Reset the peak resident set size ("high water mark") to
        the process's current resident set size value.
Run Code Online (Sandbox Code Playgroud)

/proc/[pid]/status可以使用->VmHWM或读出 HWM/peak RSS getrusage()

补丁 RFC