How to record the RAM usage during Python and C++ run time?

Ask Ubuntu Asked by GeneralCode on August 6, 2020

I want to compare the RAM consumption for a Python versus C++ implementation of a code I have written. Essentially I am looking for a command like:

<record ram> python3


<record this runtime ram> g++ main.cpp

Is is possible to record RAM for a specific task like this in Linux Ubuntu?

Thank you for your time.

One Answer

You can read the text file /prof/self/stat after all the memory allocation takes place. Its fields are described here. In linux we refer to two kinds of memory:

  • Resident Set Size (RSS) is how much memory is allocated to the process and in in RAM,
  • Virtual Memory Size (VMZ) is how much memory is allocated including swapped out memory and memory allocated by shared libraries.

From the stat file read vsize and rss. After reading this you can find the size in kb using the following in C++.

#include <unistd.h>

long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
vm_usage     = vsize / 1024.0;
resident_set = rss * page_size_kb;

In Python you can use os.sysconf("SC_PAGE_SIZE") to get the PAGE_SIZE and do the equivalent calculation.

You can also explore Valgrind for this purpose.

Answered by turbulence on August 6, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP