0

I am running C++ code on Ubuntu. I need to log current memory utilization. After quick reading linux man page, I came up with following:

double getTotalMemory() {
    std::ifstream meminfo("/proc/meminfo");
    if (!meminfo) {
        std::cerr << "Error opening /proc/meminfo." << std::endl;
        return -1.0;
    }

    double totalMemory = 0.0;
    std::string line;
    while (std::getline(meminfo, line)) {
        if (line.find("MemTotal:") == 0) {
            std::istringstream iss(line);
            std::string memType;
            int memSize;
            iss >> memType >> memSize;
            totalMemory = static_cast<double>(memSize);
            break;
        }
    }

    meminfo.close();
    return totalMemory;
}

double availableMemoryKB = static_cast<double>(sysconf(_SC_AVPHYS_PAGES) * sysconf(_SC_PAGESIZE)) / 1024.0;

// Calculate memory utilization percentage
double memoryUtilization = 100.0 - (availableMemoryKB / totalMemoryKB) * 100.0;

However, this answer gives many different approaches. Am I severely wrong with my approach?

MsA
  • 2,599
  • 3
  • 22
  • 47
  • The Q&A you link to seems to be about logging memory utilization for the current process so it's not the same as what you are doing. – Ted Lyngmo Aug 20 '23 at 16:46
  • Aah, I see. But is my logic look OK? – MsA Aug 20 '23 at 18:54
  • If you want to get the system totals, I guess it could work. You could probably simplify it by using `MemTotal`, `MemFree` and `MemAvailable` directly. – Ted Lyngmo Aug 20 '23 at 19:04

0 Answers0