Skip to content

Instantly share code, notes, and snippets.

@serge1
Created November 14, 2022 14:30
Show Gist options
  • Save serge1/6c0af0ee789c421897ae9dafc8240701 to your computer and use it in GitHub Desktop.
Save serge1/6c0af0ee789c421897ae9dafc8240701 to your computer and use it in GitHub Desktop.
Measures the current (and peak) resident and virtual memories usage of Linux C/C++ process
/*
* Measures the current (and peak) resident and virtual memories
* usage of your linux C process, in kB
*/
void getMemory( int* currRealMem,
int* peakRealMem,
int* currVirtMem,
int* peakVirtMem )
{
// stores each word in status file
char buffer[1024] = "";
// linux file contains this-process info
FILE* file = fopen( "/proc/self/status", "r" );
// read the entire file
while ( fscanf( file, " %1023s", buffer ) == 1 ) {
if ( strcmp( buffer, "VmRSS:" ) == 0 ) {
fscanf( file, " %d", currRealMem );
}
if ( strcmp( buffer, "VmHWM:" ) == 0 ) {
fscanf( file, " %d", peakRealMem );
}
if ( strcmp( buffer, "VmSize:" ) == 0 ) {
fscanf( file, " %d", currVirtMem );
}
if ( strcmp( buffer, "VmPeak:" ) == 0 ) {
fscanf( file, " %d", peakVirtMem );
}
}
fclose( file );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment