如何从C ++程序中测量内存使用情况?

时间:2011-02-25 18:01:30

标签: c++ memory-management

对于c ++程序,是否有可能跟踪程序一次使用多少内存?

例如,带有原型的函数:

int getEstimatedTotalMemoryUsage();

我想如果不可能,那么就必须离开程序,进行系统调用并从那里检查结果。如果是这样,有哪些工具可用于此类目的?假设这样的事情是可能的,那就是。

编辑:我正在使用linux,可以为你做任何工具吗?

4 个答案:

答案 0 :(得分:34)

是 - 使用POSIX getrusage。来自Linux man page

  

概要

#include <sys/time.h>
#include <sys/resource.h>

int getrusage(int who, struct rusage *usage);
     

描述

     

getrusage() 会返回 RUSAGE_SELF {{ 的当前资源使用情况1}} 即可。前者要求当前流程使用的资源,后者用于已终止并等待的子女的资源。

RUSAGE_CHILDREN

答案 1 :(得分:2)

我今天想要这个,我自己,所以在这里分享测试结果。我相信在任何unix盒子上调用getmem()都会做OP所要求的。用非常通用的C语言编写,它将在C或C ++中工作。

// Calling function must free the returned result.
char* exec(const char* command) {
  FILE* fp;
  char* line = NULL;
  // Following initialization is equivalent to char* result = ""; and just
  // initializes result to an empty string, only it works with
  // -Werror=write-strings and is so much less clear.
  char* result = (char*) calloc(1, 1);
  size_t len = 0;

  fflush(NULL);
  fp = popen(command, "r");
  if (fp == NULL) {
    printf("Cannot execute command:\n%s\n", command);
    return NULL;
  }

  while(getline(&line, &len, fp) != -1) {
    // +1 below to allow room for null terminator.
    result = (char*) realloc(result, strlen(result) + strlen(line) + 1);
    // +1 below so we copy the final null terminator.
    strncpy(result + strlen(result), line, strlen(line) + 1);
    free(line);
    line = NULL;
  }

  fflush(fp);
  if (pclose(fp) != 0) {
    perror("Cannot close stream.\n");
  }
  return result;
}

int getmem() {
  pid_t pid = getpid();
  char cmd[64];
  snprintf(cmd, 64, "/bin/ps -p %d -o size", pid);
  char* result = exec(cmd);
  if (!result) {
    return 0;
  }
  // Find first newline.
  int pos = 0;
  while (result[pos] != '\n') {
    pos++;
  }
  // Remove the final newline.
  result[strlen(result) - 1] = '\0';
  // Convert to integer.
  int size = atoi(result + pos + 1);
  free(result);
  return size;
}

从技术上讲,我认为printf(...)行应该是fprintf(stderr,...),但我倾向于将stderr重定向到某些特定于环境的日志记录原因,这就是我编译和测试的方法。代码,所以我要逐字复制以避免破损。

答案 2 :(得分:0)

获取您的PID:pid_t getpid(void); // unistd.h

解析/proc/<id>/smaps

如果您不关心mem中的共享库,可能会更简单

ps -p <id> -o %mem

进行系统调用

答案 3 :(得分:0)

这里是测量Windows上进程使用的内存的示例。

#include <windows.h>
#include <Psapi.h>

// [...]

PROCESS_MEMORY_COUNTERS memCounter;
BOOL result = K32GetProcessMemoryInfo(GetCurrentProcess(), &memCounter, sizeof(memCounter));
std::cout << "WorkingSetSize " << memCounter.WorkingSetSize << std::endl;

返回值https://docs.microsoft.com/en-gb/windows/win32/api/psapi/ns-psapi-process_memory_counters的说明