太阳不下山 发表于 2021-7-6 18:04:38

c++获取当前进程内存

#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 = '\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;
    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;
}
  

  
文档来源:51CTO技术博客https://blog.51cto.com/u_14587161/2993546
页: [1]
查看完整版本: c++获取当前进程内存