Simple example of tracking memory using getrusage

There is no real purpose to this post, as I rarely if ever write C code for any useful purpose anymore.

However, what I do use it for is better understanding Linux system calls and other various operations in the kernel. In this case, the simple code will allocate and populate memory segments, and use the getrusage() system call to show how much memory is in use.

#include 
#include 
#include 
#include 

int main() {
  int i = 0;
  struct rusage r_usage;
  while (++i <= 10) {
    void *m = malloc(20*1024*1024);
    memset(m,0,20*1024*1024);
    getrusage(RUSAGE_SELF,&r_usage);
    printf("Memory usage = %ld\n",r_usage.ru_maxrss);
    sleep (3);
  }
  printf("\nAllocated memory, sleeping ten seconds after which we will check again...\n\n");
  sleep (10);
  getrusage(RUSAGE_SELF,&r_usage);
  printf("Memory usage = %ld\n",r_usage.ru_maxrss);
  return 0;
}

2 comments for “Simple example of tracking memory using getrusage

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.