bubulik has asked for the wisdom of the Perl Monks concerning the following question:

Greetings! A simple requirement: how can I check the system's current RAM availability? In other words, I just want a snapshot of the current memory usage of the system to be taken and return the amount of available memory. Thnx

Replies are listed 'Best First'.
Re: current RAM availability
by ambrus (Abbot) on Oct 24, 2004 at 09:55 UTC

    Here's the fastest solution under linux. Note that sysinfo(2) says that since Linux 2.3.23 (i386), 2.3.48 (all architectures) the results are returned in $s[13] bytes units, not bytes. I, however, have Linux 2.4.25-gentoo here, and it returns the data in bytes so I assume that convention. In the following code, $t is the total memory, $f is the amount of free memory, not including swap or himem (which is the memory over 4G(?) on 32-bit systems).

    sub __NR_sysinfo(){116} syscall(__NR_sysinfo, $s = pack("x256")) and d +ie $!; @s = unpack("l!L!9S!L!2I!", $s); ($t, $f) = @s[4, 5]; printf " +%.0fK used memory\n", ($t-$f)/1024;
Re: current RAM availability
by zentara (Cardinal) on Oct 24, 2004 at 13:48 UTC
    Use Linux::MemInfo and extract what part you want.
    #!/usr/bin/perl use Linux::MemInfo; %hash = get_mem_info(); foreach(sort keys %hash) { print "$_ = $hash{$_} \n"; }

    I'm not really a human, but I play one on earth. flash japh
Re: current RAM availability
by strat (Canon) on Oct 24, 2004 at 09:15 UTC
    Which operating system? I don't know a plattform independend way...

    Best regards,
    perl -e "s>>*F>e=>y)\*martinF)stronat)=>print,print v8.8.8.32.11.32"

Re: current RAM availability
by ambrus (Abbot) on Oct 24, 2004 at 09:28 UTC

    You'll have to decide whether you want to include swap usage in it or not.

    In linux, parse /proc/meminfo. In other unix systems, you might try to parse the output of free, or top bn1 if free doesn't work for some reason. (Update: it seems that free doesn't exist on solaris. top does work, but its arguments are different from the linux version.)

Re: current RAM availability
by meetraz (Hermit) on Oct 24, 2004 at 20:34 UTC
    Here is one way of doing it on Windows:

    use strict; use Win32::OLE qw(in); my $WMI = Win32::OLE->GetObject("winmgmts:") or die ("Could not create WMI object."); my $OS_Col = $WMI->InstancesOf('Win32_OperatingSystem') or die ("Could not get OS instances."); foreach my $OS (in $OS_Col) { printf "Free Physical Memory: %10u kB\n", $OS->{FreePhysicalMemor +y}; printf "Free Virtual Memory: %10u kB\n", $OS->{FreeVirtualMemory +}; printf "Total Virtual Memory: %10u kB\n", $OS->{TotalVirtualMemor +ySize}; printf "Total Visible Memory: %10u kB\n", $OS->{TotalVisibleMemor +ySize}; }