I always wanted to know memory usage of particular structure in my perl programs. Recently, I noticed that Storable file size corresponds nicely to memory usage of my application, so I used that as a hint of memory usage before loading data.
Then, I decided to show usage of already loaded data. Using Devel::Size total_size seemed like the way to go, but it's much slower than simple Storable piping to /dev/null
Rate total_size storable
total_size 4.04/s -- -70%
storable 13.5/s 234% --
using this code
use Benchmark qw(:all);
use Devel::Size;
use Storable;
sub _storable_size {
open(my $fh, '|-', 'cat > /dev/null');
Storable::store_fd $_[0], $fh;
tell($fh);
}
my $o;
$o->{$_} = rand() foreach ( 'a' .. 'z' );
my $hash;
$hash->{$_} = $o foreach ( 0 .. 100_000 );
cmpthese( 100, {
'total_size' => sub { Devel::Size::total_size( $hash ) },
'storable' => sub { _storable_size( $hash ) },
});
To be honest, I didn't expect so much difference. I can probably setup pipes myself to get a bit more performance, but I would really like to know alternative ways to find out perl memory usage without performance impact.
I'm experimenting with this code in gist on github as a log of things that I tried.