Skip to content

Instantly share code, notes, and snippets.

@TysonRayJones
Last active December 18, 2017 14:36
Show Gist options
  • Select an option

  • Save TysonRayJones/15083e2ad3025451e7eee5f58589a543 to your computer and use it in GitHub Desktop.

Select an option

Save TysonRayJones/15083e2ad3025451e7eee5f58589a543 to your computer and use it in GitHub Desktop.
A guide on using the Linux process memory profiler in C

Measure memory of a Linux process in C

Get code from here.

The header file

#include "memorymeasure.h"

provides a single function getMemory which returns the current and peak, real and virtual memories (in bytes, accurate to ~kilobytes) used by your C code's Linux process.

Call via

unsigned long currRealMem, peakRealMem, currVirtMem, peakVirtMem;

int success = getMemory(&currRealMem, &peakRealMem, &currVirtMem, &peakVirtMem);

where success = 0 if memory fetching was successful (if the needed linux process files exist).


Real memory (resident set size) is the amount of physical RAM your process is using, and virtual memory is the size of the memory address space your process is using. Linux chooses what in your virtual memory gets to reside in RAM. Note that in addition to your program data, these memories include the space taken up by your code itself, and any libraries your code is using (which may be shared by other running processes, skewing your usage). A good explanation can be found here.

Peak memory is the maximum amount of memory your process has used over its lifetime so far.


This function works by reading /proc/self/status which linux populates with info about your running process. It uses fields

Output status Field Description
currRealMem VmRSS Resident set size
peakRealMem VmHWM Peak resident set size ("high water mark")
currVirtMem VmSize Virtual memory size
peakVirtMem VmPeak Peak virtual memory size

taken from under /proc/[pid]/status on the proc man page.

See procps for a much more versatile tool in analysing the linux process table.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment