After starting to do Tk programming, I realized how easy it is to make a lousy design which leaks memory, especially with
photo objects. So I got tired of running top and peeking back and forth, or repeatedly running ps.
After looking at all the alternatives, I settled on directly reading from /proc. It seemed to run the best out of all tried methods, which I monitored with strace. Look in the upper left corner.
UPDATE May-7-2005 added a MeM.pm version
UPDATE July 12 2011 fixed the way pid is obtained for Perl 5.14.1. $$ is gone, replaced with POSIX::getpid()
#!/usr/bin/perl
use warnings;
use strict;
use Tk;
use POSIX qw(getpid); #update for Perl 5.14.1
##########################################################
# you can put it in your development programs like this:
# my $memmonitor = 1;
# if($memmonitor){
# my $pid = $$;
# if(fork() == 0){exec("./memmonitor $pid")}
# }
######################################################
#my $pid = shift || $$;
my $pid = getpid();
my $mw = new MainWindow;
$mw->overrideredirect(1);
my $t = $mw->Label(-text=>'', -bg=>'black', -fg=>'yellow')->pack;
my $id = Tk::After->new($mw,1000,'repeat',\&refresh);
MainLoop;
sub refresh{
my @size = split "\n", `cat /proc/$pid/status`;
(my $vmsize) = grep {/VmSize/} @size;
my (undef,$size) = split "\t",$vmsize;
$t->configure(-text=>"PID: $pid -> $size");
if($size eq ''){Tk::exit}
}
__END__
#################################################
Here is a modular version, save the file below as MeM.pm
package MeM;
use warnings;
use strict;
use POSIX qw(getpid);
#my $pid =$$;
my $pid = getpid();
if (fork() == 0) {
require Tk;
my $mw = new MainWindow;
$mw->overrideredirect(1);
$mw->geometry('-0-0');
my $t = $mw->Label(-text => '', -bg => 'black', -fg => 'yellow')->
+pack;
$0 = 'MeM';
my $id = Tk::After->new($mw, 1000, 'repeat', [ \&refresh, $pid ]);
Tk::MainLoop();
sub refresh {
my $pid = shift;
#asmutils version of cat
# my @size = split "\n", `/home/zentara/perl5lib/cat /proc/$pid
+/status`;
my @size = split "\n", `cat /proc/$pid/status`;
(my $vmsize) = grep { /VmSize/ } @size;
my (undef, $size) = split ' ', $vmsize;
$t->configure(-text => "PID: $pid -> $size");
if ($size eq '') { exit }
}
}
1;