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!

Related Questions

Migrate from mythbuntu 18.04 to xubuntu 20.04

2  Asked on January 9, 2021 by pssturges


Install Ubuntu20.04 in Dell(ALIENWARE M17 2020):

2  Asked on January 9, 2021 by yiping-liu


Unity 3D editor window filled with pink color

2  Asked on January 9, 2021 by afsal


BIOS update – Ubuntu 20.04 – Asus A320m-k

0  Asked on January 8, 2021 by mmiroslav13


HyperX Headset not working

0  Asked on January 7, 2021 by notonline


Only Dummy-Output audio after restart

0  Asked on January 7, 2021 by linuxidiot44ab


My latte-dock does not reappear after auto hiding

0  Asked on January 6, 2021 by thulashitharan-d


New Ryzen 3950X segfaults and XID errors

0  Asked on January 6, 2021 by fsociety


How to install some .deb packages from cache with apt?

1  Asked on January 5, 2021 by archisman-panigrahi


Ubuntu 15.10: blurry texts and images

3  Asked on January 5, 2021 by th3_z3r0


Expand volume size in Ubuntu 18.04 VPS | Xen

0  Asked on January 4, 2021 by bongda668


Uninstall Ubuntu Studio

0  Asked on January 4, 2021 by noah-strong


veth.ko missing

0  Asked on January 4, 2021 by seffyroff


Ask a Question

Get help from others!

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