0

I have created a trie in C++ and inserted 1,000,000 words to it. Is there a way to get the free memory before and after the creation / allocation of the trie to have an estimate of how much memory this data structure occupies?

Basically I am searching something like

Runtime.getRuntime().totalMemory()  

that Java has.

I am using Ubuntu 64bit and gcc, so even a gcc based solution without portability is good enough for me.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Alexandros
  • 2,160
  • 4
  • 27
  • 52
  • possible duplicate of [How to get available memory C++/g++?](http://stackoverflow.com/questions/2513505/how-to-get-available-memory-c-g) – Etherealone Mar 12 '14 at 20:37
  • It is not a duplicate. Because the question you mention always returns the same number. I want the free_pages x page_size and not total_pages x page_size – Alexandros Mar 12 '14 at 20:57

1 Answers1

3

On Linux, look in /proc/getpid()/statm, e.g.

$ cat /proc/$$/statm
4128 728 443 176 0 291 0

you want the sixth number (291 in this case) - that's the size of the data section.

(For avoidance of doubt, within your program you could read that programmatically.)

Update: shell command was to illustrate the contents of the statm file. You wouldn't do that from within your program: just read /proc/self/statm and grab the sixth field: something like (C, rather than C++, but you could use iostream if you so desire, and a bit ugly, but it illustrates the principle):

size_t read_statm (void)
{
  unsigned a, b, c, d, e, f;

  FILE * const fp = fopen ("/proc/self/statm", "r");

  if (NULL == fp)
  {
    perror ("fopen");
    return (size_t)0;
  }

  if (6 != fscanf (fp, "%u%u%u%u%u%u", &a, &b, &c, &d, &e, &f))
  {
    perror ("scanf");
    (void)fclose (fp);
    return (size_t)0;
  }

  (void)fclose (fp);
  return (size_t)f;
}
user3392484
  • 1,929
  • 9
  • 9