评论

收藏

[C++] c++获取当前进程内存

编程语言 编程语言 发布于:2021-07-06 18:04 | 阅读数:424 | 评论:0

#include <unistd.h>
#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
int parseLine(char *line) {
  // This assumes that a digit will be found and the line ends in " Kb".
  int i = strlen(line);
  const char *p = line;
  while (*p < '0' || *p > '9') p++;
  line[i - 3] = '\0';
  i = atoi(p);
  return i;
}
// 虚拟内存和物理内存,单位为kb
typedef struct {
  uint32_t virtualMem;
  uint32_t physicalMem;
} processMem_t;
processMem_t GetProcessMemory() {
  FILE *file = fopen("/proc/self/status", "r");
  char line[128];
  processMem_t processMem;
  while (fgets(line, 128, file) != NULL) {
    if (strncmp(line, "VmSize:", 7) == 0) {
      processMem.virtualMem = parseLine(line);
      break;
    }
    if (strncmp(line, "VmRSS:", 6) == 0) {
      processMem.physicalMem = parseLine(line);
      break;
    }
  }
  fclose(file);
  return processMem;
}
int main(){
  std::cout<<"physicalMem: "<< GetProcessMemory().physicalMem<<std::endl;
  std::cout<<"virtualMem: "<< GetProcessMemory().virtualMem<<std::endl;
  for (int i = 0; i < 1000000; ++i)
  {
    usleep(1);
    int *p = new int(3);
    std::cout << "p: " << *p << std::endl;
    std::cout<<"physicalMem: "<< GetProcessMemory().physicalMem<<std::endl;
    std::cout<<"virtualMem: "<< GetProcessMemory().virtualMem<<std::endl;
  }
  return 0;
}
  

  
关注下面的标签,发现更多相似文章