Skip to content

Instantly share code, notes, and snippets.

@PolarNick239
Last active March 6, 2017 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PolarNick239/ab703902abaea34ba4a1a969143f9ad6 to your computer and use it in GitHub Desktop.
Save PolarNick239/ab703902abaea34ba4a1a969143f9ad6 to your computer and use it in GitHub Desktop.
Function to measure available memory on Linux, can be easily adopted to get any value from /proc/meminfo
#include <string.h>
#include <cstdlib>
bool get_memavailable_from_meminfo(size_t &memavailable)
{
const int LINE_LEN = 512;
char str[LINE_LEN];
FILE *fp = fopen("/proc/meminfo","rt");
if (fp == NULL) {
// perror("Cannot open /proc/meminfo");
return false;
}
while (true) {
if (fgets(str, LINE_LEN, fp) == NULL) {
fclose(fp);
return false;
}
if (!strncmp(str, "MemAvailable:", strlen("MemAvailable:"))) {
break;
}
}
memavailable = (size_t) atoll(str + strlen("MemAvailable:")) * 1024; // Convert kilobytes to bytes
fclose(fp);
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment