Skip to content

Instantly share code, notes, and snippets.

@skihero
Created November 5, 2014 09:44
Show Gist options
  • Save skihero/7983a8bd8f1c0f33256b to your computer and use it in GitHub Desktop.
Save skihero/7983a8bd8f1c0f33256b to your computer and use it in GitHub Desktop.
mem_info extraction in perl
my @meminfo = `/bin/cat /proc/meminfo`;
foreach (@meminfo) {
chomp;
if (/^Mem(Total|Free):\s+(\d+) kB/) {
my $counter_name = $1;
if ($counter_name eq 'Free') {
$free_memory_kb = $2;
}
elsif ($counter_name eq 'Total') {
$total_memory_kb = $2;
}
}
elsif (/^(Buffers|Cached|SReclaimable):\s+(\d+) kB/) {
$caches_kb += $2;
}
}
$used_memory_kb = $total_memory_kb - $free_memory_kb;
/*
The meminfo on a linux system looks like this
cat /proc/meminfo
MemTotal: 33570880 kB
MemFree: 17162456 kB
Buffers: 487780 kB
Cached: 7907992 kB
SwapCached: 0 kB
Active: 10313908 kB
Inactive: 2921112 kB
Active(anon): 4937860 kB
Inactive(anon): 536140 kB
Active(file): 5376048 kB
Inactive(file): 2384972 kB
Unevictable: 0 kB
Mlocked: 0 kB
SwapTotal: 16776664 kB
SwapFree: 16776664 kB
Dirty: 960 kB
Writeback: 0 kB
AnonPages: 4839136 kB
Mapped: 751596 kB
Shmem: 634888 kB
Slab: 2176696 kB
SReclaimable: 2096216 kB
SUnreclaim: 80480 kB
KernelStack: 9160 kB
PageTables: 0 kB
NFS_Unstable: 0 kB
Bounce: 0 kB
WritebackTmp: 0 kB
CommitLimit: 33562104 kB
Committed_AS: 17407816 kB
VmallocTotal: 34359738367 kB
VmallocUsed: 6384 kB
VmallocChunk: 34359727640 kB
HardwareCorrupted: 0 kB
DirectMap4k: 33554432 kB
DirectMap2M: 0 kB
Alternate strategy to extract the same details is to use the vmstat:
my $command_line = `vmstat | tail -1 | awk '{print \$4,\$5}'`;
chomp $command_line;
my @memlist = split(/ /, $command_line);
# Define the calculating scalars
$used_memory_kb = $memlist[0]/1024;
$free_memory_kb = $memlist[1]/1024;
$total_memory_kb = $used_memory_kb + $free_memory_kb;
Note: Scalar conversion
vmstat
procs -----------memory---------- ---swap-- -----io---- -system-- -----cpu------
r b swpd free buff cache si so bi bo in cs us sy id wa st
0 0 0 17161800 487780 10004248 0 0 0 4 0 0 0 0 100 0 0
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment