Memory usage

Hi.,
I want to know amount of memory used by a process inside the same process. For example, I am writing a program and I want to know the memory used by it from the program. So, I could do some actions (flush some unwanted data structures/ log the memory usage) in my program based on this value. I don't like to parse the top command's output.
I know this value will be stored in /proc directory. I've referred the /proc/<pid>/statm, status, stat files. But, I'm unable to find how top command is calculating that a process is utilizing x% of memory.

Hi.
I have a C program that it does:

   sprintf (fichero, "/proc/%d/statm", getpid ());
   fd = open (fichero, O_RDONLY);
   nbytes = read (fd, mem_info, sizeof (mem_info) - 1);
   close (fd);
   mem_info[nbytes] = '\0';
   nbytes = sscanf (mem_info, "%*d %d", &rss);
   printf ( "Memory: %dKb.\n",  rss * getpagesize() / 1024);

   ==> Memory: xxxx Kb.

You can also call getrusage().