How can I find out the total physical memory (RAM) of my linux box suitable to be parsed by a shell script?
If you're interested in the physical RAM, use the command dmidecode
. It gives you a lot more information than just that, but depending on your use case, you might also want to know if the 8G in the system come from 2x4GB sticks or 4x2GB sticks.
How do you determine the amount of Linux system RAM in C++?
On Linux, you can use the function sysinfo
which sets values in the following struct:
#include <sys/sysinfo.h>
int sysinfo(struct sysinfo *info);
struct sysinfo {
long uptime; /* Seconds since boot */
unsigned long loads[3]; /* 1, 5, and 15 minute load averages */
unsigned long totalram; /* Total usable main memory size */
unsigned long freeram; /* Available memory size */
unsigned long sharedram; /* Amount of shared memory */
unsigned long bufferram; /* Memory used by buffers */
unsigned long totalswap; /* Total swap space size */
unsigned long freeswap; /* swap space still available */
unsigned short procs; /* Number of current processes */
unsigned long totalhigh; /* Total high memory size */
unsigned long freehigh; /* Available high memory size */
unsigned int mem_unit; /* Memory unit size in bytes */
char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding for libc5 */
};
If you want to do it solely using functions of C++ (I would stick to sysinfo
), I recommend taking a C++ approach using std::ifstream
and std::string
:
unsigned long get_mem_total() {
std::string token;
std::ifstream file("/proc/meminfo");
while(file >> token) {
if(token == "MemTotal:") {
unsigned long mem;
if(file >> mem) {
return mem;
} else {
return 0;
}
}
// Ignore the rest of the line
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
return 0; // Nothing found
}
Get total physical memory in Python
your best bet for a cross-platform solution is to use the psutil package (available on PyPI).
import psutil
psutil.virtual_memory().total # total physical memory in Bytes
Documentation for virtual_memory
is here.
How can I measure the actual memory usage of an application or process?
With ps
or similar tools you will only get the amount of memory pages allocated by that process. This number is correct, but:
does not reflect the actual amount of memory used by the application, only the amount of memory reserved for it
can be misleading if pages are shared, for example by several threads or by using dynamically linked libraries
If you really want to know what amount of memory your application actually uses, you need to run it within a profiler. For example, Valgrind can give you insights about the amount of memory used, and, more importantly, about possible memory leaks in your program. The heap profiler tool of Valgrind is called 'massif':
Massif is a heap profiler. It performs detailed heap profiling by taking regular snapshots of a program's heap. It produces a graph showing heap usage over time, including information about which parts of the program are responsible for the most memory allocations. The graph is supplemented by a text or HTML file that includes more information for determining where the most memory is being allocated. Massif runs programs about 20x slower than normal.
As explained in the Valgrind documentation, you need to run the program through Valgrind:
valgrind --tool=massif <executable> <arguments>
Massif writes a dump of memory usage snapshots (e.g. massif.out.12345
). These provide, (1) a timeline of memory usage, (2) for each snapshot, a record of where in your program memory was allocated. A great graphical tool for analyzing these files is massif-visualizer. But I found ms_print
, a simple text-based tool shipped with Valgrind, to be of great help already.
To find memory leaks, use the (default) memcheck
tool of valgrind.
Get system memory information from julia
The built-in Sys
module contains functions dedicated to retrieving system information.
julia> VERSION
v"1.0.0"
julia> Sys.total_memory() / 2^20
8071.77734375
julia> Sys.free_memory() / 2^20
5437.46484375
julia> Sys.CPU_NAME
"haswell"
julia> Sys.
ARCH KERNEL WORD_SIZE eval isexecutable set_process_title
BINDIR MACHINE __init__ free_memory islinux total_memory
CPU_NAME SC_CLK_TCK _cpu_summary get_process_title isunix uptime
CPU_THREADS STDLIB _show_cpuinfo include iswindows which
CPUinfo UV_cpu_info_t cpu_info isapple loadavg windows_version
JIT WINDOWS_VISTA_VER cpu_summary isbsd maxrss
julia> # Above after pressing Tab key twice
While it does not support all of the information provided by top
, it will hopefully provide the information you are looking for.
exact total memory usage in linux that equals to system monitor
GNOME system monitor uses libgtop
to retrieve memory information for various platforms. For Linux it uses sysdeps/linux/mem.c
2 where the routine is as follows:
Strings like "MemTotal" are headings in /proc/meminfo
.
…
buf->total = get_scaled(buffer, "MemTotal:");
buf->free = get_scaled(buffer, "MemFree:");
buf->used = buf->total - buf->free;
buf->shared = 0;
buf->buffer = get_scaled(buffer, "Buffers:");
buf->cached = get_scaled(buffer, "Cached:");
buf->user = buf->total - buf->free - buf->cached - buf->buffer;
The memory reported in the application is buf->user
. More precisely in src/load-graph.cpp
1 by:
mempercent = (float)mem.user / (float)mem.total;
set_memory_label_and_picker(GTK_LABEL(graph->labels.memory),
GSM_COLOR_BUTTON(graph->mem_color_picker),
mem.user, mem.total, mempercent);
Related Topics
Shgetknownfolderpath Equivalent API in Linux
How to Find What Version of Libstdc++ Library Is Installed on Your Linux MAChine
Is a Moved-From Vector Always Empty
What's the Meaning of Exception Code "Exc_I386_Gpflt"
Difference Between *(Pointer + Index) and Pointer[]
How to Pass Auto as an Argument in C++
Should We Pass a Shared_Ptr by Reference or by Value
Writing Universal Memoization Function in C++11
Create Window Without Title Bar
Does Vector::Erase() on a Vector of Object Pointers Destroy the Object Itself
What Default Promotions of Types Are There in the Variadic Arguments List
Purpose of Trigraph Sequences in C++
How to Find and Replace String
G++ Linking Order Dependency When Linking C Code to C++ Code