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

Hi monks

How to find the size of memory taking the executing script, see below example

open(FH,"file.txt") or die "file not found"; my $line=0; my %hash = undef; while(<FH>) { $hash{$line} = undef; #6ht line $line++; } close FH; ##### # Here i want print the total memory occupied by this script ####

Actully, i running this script in windows, and observed the available memory under the physical memory in taskmanger. So gradully decreasing, that means the script taking memory, that taking memory want to print, once completed the script the available memory as normal in taskmanager. And when i commented the 6th line in script, its not taking that much memory becaz of hash.

So, please tell me, how to know the memory that dynamically allocating in the script and print the memory at end of script

Replies are listed 'Best First'.
Re: Allocated memory to Script
by BrowserUk (Patriarch) on Jul 08, 2011 at 10:50 UTC

    The simple way:

    #! perl -slw use strict; open FH, '<', $ARGV[0] or die "file not found"; my $line = 0; my %hash ; while( <FH> ) { $hash{ $line } = undef; #6ht line $line++; } close FH; print `tasklist /nh /fi "PID EQ $$"`; __END__ c:\test>junk3 junk.dat perl.exe 1128 Console 1 29 +,176 K

    That said, your code makes no sense. You are keying a hash with consecutive numbers, why not use an array? But then your values are undef, what is the point?


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Allocated memory to Script
by Anonymous Monk on Jul 08, 2011 at 10:39 UTC
    This is FAQ (Frequently Asked Question), use Devel::Size
Re: Allocated memory to Script
by Khen1950fx (Canon) on Jul 08, 2011 at 12:17 UTC
    I added Memory::Usage to BrowserUk's script. Using it is simple. To start recording, do
    $mu->record($your message here);
    To stop, do
    $mu->record->($msg here);
    To insert the results at the end, there are a couple of ways that I like. I prefer "state()" which returns an arrayref.
    #! perl -sl use strict; use warnings; use Memory::Usage; use Data::Dump qw(dump); my $mu = Memory::Usage->new(); $mu->record('start =>'); open FH, '<', $ARGV[0] or die "file not found"; my $line = 0; my %hash ; while( <FH> ) { $hash{ $line } = undef; $line++; } close FH; $mu->record('end =>'); print dump($mu->state());
      I added Memory::Usage to BrowserUk's script

      That's all very well, but as the module doesn't work on Windows, it is entirely useless.

        According to this, it does work on Windows.