Hatena::ブログ(Diary)

ymkoの日記

2011-11-06

メモリ使用率を求める

#!/usr/bin/perl
use strict;
use warnings;

my %meminfo = get_meminfo();
system("free");

my ($total, $free, $buffers, $cached) =
        @meminfo{'MemTotal', 'MemFree', 'Buffers', 'Cached'};
my $used = $total - ($free + $buffers + $cached);
my $used_per = sprintf("%.2f", $used * 100 / $total);

warn "total=[$total] free=[$free] buffers=[$buffers] cached=[$cached]\n";
warn "used=[$used]\n";
warn "used_per=[$used_per\%]\n";

sub get_meminfo
{
        my %hash;
        open my $fh, "<", "/proc/meminfo";
        while (<$fh>) {
                chomp;
                next unless $_;
                next if $_ eq "";
                my ($key, $val) = split /:/;
                my $size = 0;
                if ($val =~ /(\d+)/) {
                        $size = $1;
                }
                #warn "[$key][$size]\n";
                $hash{$key} = $size;
        }
        close $fh;
        return %hash;
}
__END__
             total       used       free     shared    buffers     cached
Mem:        509792     472652      37140          0      17228     412040
-/+ buffers/cache:      43384     466408
Swap:      2048276         84    2048192
total=[509792] free=[37272] buffers=[17228] cached=[412040]
used=[43252] <- freeコマンド used の二段目に相当
used_per=[8.48%]